2014-03-01 42 views
3

我有類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')) 
+0

爲什麼你指定主要/輔助連接條件爲字符串? – Miguel

+0

謝謝你,是一個愚蠢的錯誤 – user3185958

回答

3

因爲你的模型具有所有必要的規定ForeignKey S,sqlachemy是足夠聰明,找出參數primaryjoinsecondaryjoin本身。因此,這應該只是罰款:

favorites = db.relationship('Listing', 
    secondary = favorites_table, 
    # primaryjoin = 'favorites_table.c.user_id == User.id', 
    # secondaryjoin = 'favorites_table.c.listing_id == Listing.id', 
    backref = db.backref('users', lazy = 'dynamic'), 
    lazy = 'dynamic', 
    ) 

如果你真的希望是明確的,你可以取消兩行上面完全相同的結果。請注意,我在每個指定的id列之前添加了一個型號名稱。

請注意,您在favorites_table關係表列user_idListing.idlisting_id -> User.id,而它看起來應該是周圍的其他方法。

+0

非常感謝你,他們確實切換。 – user3185958

+0

@vanjoin/secondaryjoin到底做了什麼? – Zion