2017-02-13 55 views
0

我正在通過Miguel Grinberg的燒瓶書。使用Flask-SQLAlchemy定義關聯對象,相關表的順序?

在第12章中,他定義了一個關聯對象跟隨跟隨者和跟隨者,都映射到一個用戶,以及添加關注者並遵循Users類。

我本來把關聯表的用戶表後,當我跑蟒蛇manage.py DB升級得到了一個錯誤:

line 75, in User followed = db.relationship('Follow', foreign_keys= [Follow.follower_id], 
NameError: name 'Follow' is not defined 

然後我感動的關聯對象類按照以上類用戶的定義,並重新運行遷移。這一次它工作。

有人可以解釋這個原因嗎?

這兩個類定義似乎都需要另一個。

爲什麼我應該知道關於flask-sqlalchemy,sqlalchemy或ORM的一般情況?

SQLAlchemy文檔說"we can define the association_table at a later point, as long as it’s available to the callable after all module initialization is complete"和關係是在類本身中定義的。

也就是說,您正在使用的情況和association_table顯示兩個獨立模型之間的關係。我在Flask-SQLAlchemy或SQLAlchemy文檔中沒有看到關於這種情況的任何信息,但是當我看到它時很可能沒有認出答案。

class Follow(db.Model): 
    __tablename__ = 'follows' 
    follower_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) 
    followed_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True) 
    timestamp = db.Column(db.DateTime, default=datetime.utcnow) 

或者,也許順序並不在所有問題,而我misattributing一個問題:

class User(UserMixin, db.Model): 
    __tablename__ = 'users' 
    ... 
    followed = db.relationship('Follow', 
          foreign_keys=[Follow.follower_id], 
          backref=db.backref('follower', lazy='joined'), 
          lazy='dynamic', 
          cascade='all, delete-orphan') 
    followers = db.relationship('Follow', 
          foreign_keys=[Follow.followed_id], 
          backref=db.backref('followed', lazy='joined'), 
          lazy='dynamic', 
          cascade='all, delete-orphan') 

與定義的順序?

回答

0

首先,如果您打算在稍後使用某個類,則必須已經定義它。定義順序很重要,您不能使用尚不存在的類。

其次,sqlalchemy說你會定義第三個表來創建關係。如果使用這種方法,User和Follow類將不會訪問每個其他屬性,因此它不會導致定義順序錯誤。

最後,如果你不定義一個關聯表,那麼你必須按正確的順序放置類,以使用它們的屬性。

+0

Follow是關聯對象(我沒有使用關聯表,因爲關係是從用戶到用戶)。每個人都是一個班級,每個班級都引用另一個班級,所以無論哪個班級首先是循環班級。 –

+0

然後在用戶類之前移動Follow類,它將工作 – metmirr