gpt4 book ai didi

python - SQLAlchemy - 标签字典

转载 作者:太空狗 更新时间:2023-10-29 17:06:44 30 4
gpt4 key购买 nike

我对 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')

但我想要以下行为:

mapper(Item, items_table, properties={
# key by column
'notes': relation(...),
})

item = Item()
item.notes['color'] = 'blue'

在 SQLAlchemy 中可以吗?

谢谢

最佳答案

简单的回答是

只需使用关联代理:

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

创建测试环境:

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 = value
class 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')]

有效!! :)

关于python - SQLAlchemy - 标签字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/780774/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com