来自唯一和主外键的SQLAlchemy主键

时间:2017-08-18 07:57:44

标签: python postgresql sqlalchemy

我有两个表格,报告和出价,以及一对多的关系,报告可以有多个出价。简化报告如下:

class Report(Base):
    __tablename__ = 'reports'

    dr_nbr = Column(CHAR(14), primary_key=True)
    header_trade = Column(VARCHAR(255), unique=True)
    bids = relationship("BidDetail", lazy="dynamic")

出价表如下所示:

class BidDetail(Base):
    __tablename__ = 'bids'

    report_id = Column(CHAR(14), primary_key=True)
    report_header_trade = Column(VARCHAR(255), primary_key=True)
    __table_args__ = (ForeignKeyConstraint(
                            [report_id, report_header_trade],
                            [Report.dr_nbr, Report.header_trade]),
                     {})

我尝试了几种方法从报告导入两个密钥并用作主键。我知道当我使用来自另一个表的主外键时,我需要定义一个ForeignKeyConstraint,但是当一个外键是主键而另一个外键不起作用时。我尝试过的另一件事(通过在SO上研究类似的问题)将两个作为外键的字段传递给__table_args__作为UniqueConstraint,但我不确定我到底在做什么,它也行不通。

如何在SQLAlchemy中导入两个外键,其中一个是primary key而另一个是unique约束?

1 个答案:

答案 0 :(得分:0)

感谢@ ilja-everilä帮助回答评论中的问题。定义表的正确方法是:

class Report(Base):
__tablename__ = 'reports'

dr_nbr = Column(CHAR(14), primary_key=True)
header_trade = Column(VARCHAR(255))
__table_args__ = (UniqueConstraint(dr_nbr, header_trade),)
contacts = relationship(
                'Contact',
                secondary='report_contact_link'
)
bids = relationship("BidDetail", lazy="dynamic")

class BidDetail(Base):
__tablename__ = 'bids'

report_id = Column(CHAR(14), primary_key=True)
report_header_trade = Column(VARCHAR(255), primary_key=True)
__table_args__ = (ForeignKeyConstraint(
                        [report_id, report_header_trade],
                        [Report.dr_nbr, Report.header_trade]),
                 {})