简单的答案是 肯定的 。
只需使用关联代理:
from sqlalchemy import Column, Integer, String, Table, create_enginefrom sqlalchemy import orm, metaData, Column, ForeignKeyfrom sqlalchemy.orm import relation, mapper, sessionmakerfrom sqlalchemy.orm.collections import column_mapped_collectionfrom sqlalchemy.ext.associationproxy import association_proxy
创建一个测试环境:
engine = create_engine('sqlite:///:memory:', echo=True)meta = metaData(bind=engine)
定义表:
tb_items = Table('items', meta, Column('id', Integer, primary_key=True), Column('name', String(20)), Column('description', String(100)), )tb_notes = Table('notes', meta, Column('id_item', Integer, ForeignKey('items.id'), primary_key=True), Column('name', String(20), primary_key=True), Column('value', String(100)), )meta.create_all()
类(注意
association_proxy类中的):
class Note(object): def __init__(self, name, value): self.name = name self.value = valueclass Item(object): def __init__(self, name, description=''): self.name = name self.description = description notes = association_proxy('_notesdict', 'value', creator=Note)
对应:
mapper(Note, tb_notes)mapper(Item, tb_items, properties={ '_notesdict': relation(Note, collection_class=column_mapped_collection(tb_notes.c.name)), })
然后测试一下:
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'}
但是,那些在注释表中吗?
>>> print list(tb_notes.select().execute())[(1, u'color', u'orange'), (1, u'data', u'none'), (1, u'size', u'big')]
有用!!:)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)