我想使用经典的映射器将使用dicts作为其内部数据结构的类映射到一些常规关系表:
# my class
class Order:
def __init__(self, id: str, lines: dict):
self.lines = lines
# order lines are a mapping of product code to quantity ordered,
# eg: Order(id='order-id', lines={'product1': 23, 'product2', 12})
# my tables
order = sqlalchemy.Table(
'order', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
)
order_lines = sqlalchemy.Table(
'order_lines', metadata,
Column('order_id', ForeignKey('order.id'), primary_key=True),
Column('product_code', String(255), primary_key=True),
Column('quantity', Integer),
)
现在,如何配置mapper
以便将其连接到order_lines表,然后将order_lines转换为将product_code列映射到数量列的字典?
[edit]:也许像attribute_based_collection
这样的东西可以工作吗? https://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#proxying-to-dictionary-based-collections