nesalexy
nesalexy

Reputation: 878

Sqla flask two ForeignKey the same table

I have a table "ProductVariant"

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)

and i cant understand how i need create a back ref in the table "Vendor"

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

i have an error:

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.

sqlalchemy.exc.AmbiguousForeignKeysError: Can't determine join between 'vendors' and 'product_variants'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.

Upvotes: 0

Views: 71

Answers (1)

Stephen Fuhry
Stephen Fuhry

Reputation: 13009

You need to specify which foreign key to reference with backref, since it's ambiguous


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"))

Upvotes: 1

Related Questions