簡體   English   中英

SQLAlchemy,自引用輔助表關聯

[英]SQLAlchemy, self-referential secondary table association

我正在嘗試在SQLAlchemy中創建“產品”對象,到目前為止,我已經使所有工作都可以接受產品的“附件”。 我所擁有的是一種產品,其中包含字段/值對的列表(例如,容量:12 L等),以及整數ID和目錄號。 我希望能夠將某些“附件”與給定的產品相關聯,而這些附件也是產品。 本質上,我只需要一個具有product_id和annex_id的關聯表,它們都引用Products表中的ID。 這是我到目前為止的內容:

product_accessories=Table('product_accesssories',Base.metadata,\
                   Column('product_id',Integer,ForeignKey('product.product_id')),\
                   Column('accessory_id',Integer,ForeignKey('product.product_id')))

class Product(Base):
    __tablename__='product'
    id=Column('product_id',Integer,primary_key=True)
    catNo=Column('catalog_number',String(20))
    fields=relationship('ProductField')
    accessories=relationship('Product',secondary=product_accessories)

我收到錯誤“無法確定關系Product.accessories的父/子表之間的聯接條件”。 我已經試着擺弄一堆,卻沒能到達任何地方。 我不想失去對產品的獨特引用,我覺得應該有一種比將配件包裝在另一類中更簡單的方法。

任何幫助將不勝感激!

import sqlalchemy as sa
from sqlalchemy import orm

products_table = sa.Table('products', metadata,
    sa.Column('id', sa.Integer(), primary_key=True),
    sa.Column('catalog_number', sa.String(20)),
)

accessories_table = sa.Table('product_accessories', metadata,
    sa.Column('product_id', sa.ForeignKey(products_table.c.id), primary_key=True),
    sa.Column('accessory_id', sa.ForeignKey(products_table.c.id), primary_key=True),
)

class Product(object):
    pass

class Accessory(object):
    pass

orm.mapper(Product, products_table, properties=dict(
    accessories=orm.relation(Accessory,
        primaryjoin=(products_table.c.id == accessories_table.c.product_id),
        secondaryjoin=(products_table.c.id == accessories_table.c.accessory_id),
    ),
))
orm.mapper(Accessory, accessories_table)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM