我有類User和Listing,我試圖創建一個多對多的關係,以便用戶可以擁有許多最喜歡的列表,上市可能會受到許多用戶的青睞。Flask幫助理解多對多關係的primaryjoin/secondaryjoin
我一直在使用this作爲參考,但這是我第一次多對多的關係,所以任何幫助,將不勝感激。
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Could not determine relationship direction for primaryjoin condition 'favorites_table.user_id = :user_id_1', on relationship User.favorites. Ensure that the referencing Column objects have a ForeignKey present, or are otherwise part of a ForeignKeyConstraint on their parent Table, or specify the foreign_keys parameter to this relationship.
models.py
favorites_table = db.Table('favorites_table',
db.Column('user_id', db.Integer, db.ForeignKey('listing.id')),
db.Column('listing_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key = True)
listings = db.relationship('Listing', backref = 'manager', lazy = 'dynamic')
favorites = db.relationship('Listing',
secondary=favorites_table, primaryjoin = ('favorites_table.c.user_id == id'),
secondaryjoin = ('favorites_table.c.listing_id == id'),
backref = db.backref('user', lazy = 'dynamic'), lazy = 'dynamic')
def favorite_listing(self, listing):
if not self.is_favorite(listing):
self.favorites.append(listing)
return self
def unfavorite_listing(self, listing):
if self.is_favorite(listing):
self.favorites.remove(listing)
return self
def is_favorite(self, listing):
return self.favorites.filter(favorites_table.c.listing_id == listing.id).count() > 0
class Listing(db.Model):
id = db.Column(db.Integer, primary_key = True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
爲什麼你指定主要/輔助連接條件爲字符串? – Miguel
謝謝你,是一個愚蠢的錯誤 – user3185958