hon*_*zas 15 python sqlalchemy
我对SQLAlchemy有疑问.如何在我的映射类中添加类似字典的属性,该属性将字符串键映射到字符串值,并将存储在数据库中(与原始映射对象在同一个表或另一个表中).我希望这添加对我的对象的任意标记的支持.
我在SQLAlchemy文档中找到了以下示例:
from sqlalchemy.orm.collections import column_mapped_collection, attribute_mapped_collection, mapped_collection
mapper(Item, items_table, properties={
# key by column
'notes': relation(Note, collection_class=column_mapped_collection(notes_table.c.keyword)),
# or named attribute
'notes2': relation(Note, collection_class=attribute_mapped_collection('keyword')),
# or any callable
'notes3': relation(Note, collection_class=mapped_collection(lambda entity: entity.a + entity.b))
})
item = Item()
item.notes['color'] = Note('color', 'blue')
Run Code Online (Sandbox Code Playgroud)
但我想要以下行为:
mapper(Item, items_table, properties={
# key by column
'notes': relation(...),
})
item = Item()
item.notes['color'] = 'blue'
Run Code Online (Sandbox Code Playgroud)
在SQLAlchemy中有可能吗?
谢谢
nos*_*klo 21
简单的答案是肯定的.
只需使用关联代理:
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
Run Code Online (Sandbox Code Playgroud)
创建测试环境:
engine = create_engine('sqlite:///:memory:', echo=True)
meta = MetaData(bind=engine)
Run Code Online (Sandbox Code Playgroud)
定义表:
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()
Run Code Online (Sandbox Code Playgroud)
类(注意association_proxy类中):
class Note(object):
def __init__(self, name, value):
self.name = name
self.value = value
class Item(object):
def __init__(self, name, description=''):
self.name = name
self.description = description
notes = association_proxy('_notesdict', 'value', creator=Note)
Run Code Online (Sandbox Code Playgroud)
制图:
mapper(Note, tb_notes)
mapper(Item, tb_items, properties={
'_notesdict': relation(Note,
collection_class=column_mapped_collection(tb_notes.c.name)),
})
Run Code Online (Sandbox Code Playgroud)
然后测试一下:
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
Run Code Online (Sandbox Code Playgroud)
打印:
{u'color': u'orange', u'data': u'none', u'size': u'big'}
Run Code Online (Sandbox Code Playgroud)
但是,那些在笔记表中的是什么?
>>> print list(tb_notes.select().execute())
[(1, u'color', u'orange'), (1, u'data', u'none'), (1, u'size', u'big')]
Run Code Online (Sandbox Code Playgroud)
有用!!:)
| 归档时间: |
|
| 查看次数: |
3652 次 |
| 最近记录: |