Python 声明式SQLAlchemy中的标记词典?
我正在使用Python 声明式SQLAlchemy中的标记词典?,python,sqlalchemy,declarative,Python,Sqlalchemy,Declarative,我正在使用sqlalchemy.ext.declarative实现一个相当大的代码库,我需要向其中一个类添加一个类似dict的属性。我所需要的与中的相同,但以声明方式。有谁对炼金术有更多的了解,能给我举个例子吗? 提前感谢…声明性只是定义事物的另一种方式。实际上,与使用分离映射相比,最终得到的环境完全相同 既然我回答了另一个问题,我也会试试这个。希望它能提供更多的选票;) 首先,我们定义类 from sqlalchemy import Column, Integer, String, Table
sqlalchemy.ext.declarative
实现一个相当大的代码库,我需要向其中一个类添加一个类似dict的属性。我所需要的与中的相同,但以声明方式。有谁对炼金术有更多的了解,能给我举个例子吗?
提前感谢…声明性只是定义事物的另一种方式。实际上,与使用分离映射相比,最终得到的环境完全相同 既然我回答了另一个问题,我也会试试这个。希望它能提供更多的选票;) 首先,我们定义类
from sqlalchemy import Column, Integer, String, Table, create_engine
from sqlalchemy import orm, MetaData, Column, ForeignKey
from sqlalchemy.orm import relation, mapper, sessionmaker
from sqlalchemy.orm.collections import column_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
Base = declarative_base(bind=engine)
class Note(Base):
__tablename__ = 'notes'
id_item = Column(Integer, ForeignKey('items.id'), primary_key=True)
name = Column(String(20), primary_key=True)
value = Column(String(100))
def __init__(self, name, value):
self.name = name
self.value = value
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True)
name = Column(String(20))
description = Column(String(100))
_notesdict = relation(Note,
collection_class=column_mapped_collection(Note.name))
notes = association_proxy('_notesdict', 'value', creator=Note)
def __init__(self, name, description=''):
self.name = name
self.description = description
Base.metadata.create_all()
现在让我们做一个测试:
Session = sessionmaker(bind=engine)
s = Session()
i = Item('ball', 'A round full ball')
i.notes['color'] = 'orange'
i.notes['size'] = 'big'
i.notes['data'] = 'none'
s.add(i)
s.commit()
print i.notes
我得到:
{u'color': u'orange', u'data': u'none', u'size': u'big'}
1 color orange
1 data none
1 size big
现在让我们检查notes表
for note in s.query(Note):
print note.id_item, note.name, note.value
我得到:
{u'color': u'orange', u'data': u'none', u'size': u'big'}
1 color orange
1 data none
1 size big
它起作用了!!:D如果您不需要查询属性,那么这个答案提供了另一种方法:我得到一个
sqlalchemy.exceptions.norReferencedTableError:找不到用于生成外键的表“items”
修复了它!必须从Note.id\u item
中删除ForeignKey('items.id')
,并在item
声明后添加Note.\uu表\uuuuuuuuuuuu.append\u约束(ForeignKeyConstraint(['id\u item'],['items.id'])
。还必须将Note.name
替换为Note.\uuu table\uu.c.name
中的项。\u notesdict
@martin:奇怪!您使用的是哪个版本的sqlalchemy?代码在我的机器上运行与上面一样。我刚刚确认,这里不需要修复。它只是在运行。@nosklo:我用的是0.4.8。如果在我的前置注释中没有循环依赖解决方案,它将无法运行。。。