SQLA烧瓶两个外键在同一个表

时间:2020-01-28 12:58:21

标签: mysql flask sqlalchemy

我有一个表格“ ProductVariant”

 val intentt = getIntent()
 var wasCreatedFromAnotherActivity = 
     intentt.getBooleanExtra("CREATED_FROM_ANOTHER_ACTIVITY",false)

我无法理解如何在“供应商”表中创建反向引用

class ProductVariant(sqla.Model, ExtendMixin, ResourcesMixin):

 vendor_id = sqla.Column(
        sqla.Integer,
        sqla.ForeignKey('vendors.id'),
        nullable=True)
    decorator_id = sqla.Column(
        sqla.Integer,
        sqla.ForeignKey('vendors.id'),
        nullable=True)

我有一个错误:

class Vendor(sqla.Model, ExtendMixin): pv_vendors = sqla.relationship( 'ProductVariant', backref='vendor') pv_decorators = sqla.relationship( 'ProductVariant', backref='vendor')

sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Vendor.pv_vendors - there are multiple foreign key paths linking the tables.  Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.

1 个答案:

答案 0 :(得分:1)

您需要指定backref引用哪个外键,因为它不明确


class ProductVariant(sqla.Model, ExtendMixin, ResourcesMixin):

    vendor_id = sqla.Column(
        sqla.Integer,
        sqla.ForeignKey('vendors.id'),
        nullable=True)

    decorator_id = sqla.Column(
        sqla.Integer,
        sqla.ForeignKey('vendors.id'),
        nullable=True)


class Vendor(sqla.Model, ExtendMixin):
    pv_vendors = sqla.relationship(
        'ProductVariant',
        backref=backref('vendor', foreign_keys="ProductVariant.vendor_id"))

    pv_decorators = sqla.relationship(
        'ProductVariant',
        backref=backref('decorator', foreign_keys="ProductVariant.decorator_id"))