【问题标题】:SQLAlchemy: can't understand this one2many relationship with composite keysSQLAlchemy:无法理解这种与复合键的 one2many 关系
【发布时间】:2012-06-24 03:06:07
【问题描述】:

我有一个像下面这样的 SQLAlchemy 模型,起初它不起作用(连接问题,然后期望一个标量而不是列表)。我在包含的版本中“修复”了它,但我真的无法理解它为什么会这样。

起初,我预计对于那些 ForeignKeys,Sizes.items relationship() 不需要显式的 primaryjoin,当我添加它时,SA 开始期待一个标量,我必须显式指定 uselist=True .

为什么这种关系不能自动检测到其中一项或两项?

class Category(Base):
    __tablename__ = 'categories'
    pk   = Column(String(6), primary_key=True)

class Item(Base):
    __tablename__ = 'items'
    pk          = Column(String(6), primary_key=True)
    category_pk = Column(String(6), ForeignKey('categories.pk') )
    size        = Column(Integer(), nullable=False)
    category    = relationship('Category', backref=backref('items'))

class Sizes(Base):
    __tablename__ = 'sizes'
    category_pk = Column(String(6), ForeignKey('categories.pk'),
                    ForeignKey('items.category_pk'), primary_key=True )
    size        = Column(Integer(), ForeignKey('items.size'), primary_key=True )
    category    = relationship('Category', backref=backref('sizes'))
    items       = relationship('Item',
        uselist=True,
        primaryjoin="and_(Sizes.category_pk==Item.category_pk, Sizes.size==Item.size)" )

【问题讨论】:

    标签: python join orm foreign-keys sqlalchemy


    【解决方案1】:

    我相信正在发生的事情是您有两个外键,而不是两列上的单个 FK。在您可以执行此操作的情况下,primary_key=True 的工作方式略有不同。

    尝试类似:

    class Category(Base):
        __tablename__ = 'categories'
        pk   = Column(String(6), primary_key=True)
    
    class Item(Base):
        __tablename__ = 'items'
        pk          = Column(String(6), primary_key=True)
        category_pk = Column(String(6), ForeignKey('categories.pk') )
        size        = Column(Integer(), nullable=False)
        category    = relationship('Category', backref=backref('items'))
    
    class Sizes(Base):
        __tablename__ = 'sizes'
        category_pk = Column(String(6), primary_key=True )
        size        = Column(Integer(), primary_key=True )
        category    = relationship('Category', backref=backref('sizes'))
        items       = relationship('Item')
    
        __table_args__ = (
            ForeignKeyConstraint(
                ["category_pk", "size"],
                ["items.category_pk", "items.size"]
            ),
        )
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2013-02-21
      • 2011-11-22
      • 2012-05-18
      • 2018-05-30
      • 2012-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多