Sqla flask два ForeignKey одной и той же таблицы - PullRequest
0 голосов
/ 28 января 2020

У меня есть таблица "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)

, и я не могу понять, как мне нужно создать обратную ссылку в таблице "Vendor"

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.

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.

1 Ответ

1 голос
/ 28 января 2020

Вам необходимо указать, какой внешний ключ ссылаться с помощью 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"))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...