python - 如何使用 SQLAlchemy 将一个类映射到多个表?

标签 python database database-design sqlalchemy

假设我有一个包含三个表的数据库结构,如下所示:

items
 - item_id
 - item_handle

attributes
 - attribute_id
 - attribute_name

item_attributes
 - item_attribute_id
 - item_id
 - attribute_id
 - attribute_value

我希望能够在 SQLAlchemy 中执行此操作:

item = Item('item1')
item.foo = 'bar'

session.add(item)
session.commit()

item1 = session.query(Item).filter_by(handle='item1').one()
print item1.foo # => 'bar'

我是 SQLAlchemy 的新手,我在文档 (http://www.sqlalchemy.org/docs/05/mappers.html#mapping-a-class-against-multiple-tables) 中找到了这个:

j = join(items, item_attributes, items.c.item_id == item_attributes.c.item_id). \
    join(attributes, item_attributes.c.attribute_id == attributes.c.attribute_id)

mapper(Item, j, properties={
    'item_id': [items.c.item_id, item_attributes.c.item_id],
    'attribute_id': [item_attributes.c.attribute_id, attributes.c.attribute_id],
})

它只能给Item添加item_id和attribute_id,不能给Item对象添加属性。

我想用 SQLAlchemy 实现的目标是可能的吗?是否有更好的方法来构建数据库以获得与“动态列”相同的行为?

最佳答案

这叫做 entity-attribute-value图案。在 SQLAlchemy 示例目录下有一个关于此的示例:vertical/ .

如果您使用的是 PostgreSQL,那么还有 hstore contrib 模块可以存储字符串到字符串的映射。如果您有兴趣,那么我有一些自定义类型的代码,可以使用它通过 SQLAlchemy 存储扩展属性。

存储自定义属性的另一种选择是将它们序列化到文本字段。在这种情况下,您将失去按属性过滤的能力。

关于python - 如何使用 SQLAlchemy 将一个类映射到多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1300433/

相关文章:

python - _mysql_exceptions.IntegrityError : (1215, 'Cannot add foreign key constraint' )

python:在本地安装matplotlib

安卓 : Expandable ListView Adapter from Database/ContentProvider/ContentResolver

sql - 数据库设计: please help me to understand relationship types

php - 如何处理自定义表单数据库

python - 如何有意使具有错误打印输出的Python代码崩溃(“IntegrationWarning”)

python - Mel 到 Python 的难度

mysql - 表之间的关系需要描述吗?

sql - 哪个数据库设计更好?

mysql - 数据库布局问题