【发布时间】:2017-07-01 00:26:06
【问题描述】:
我正在阅读 Miguel Grinberg 的 Flask 书。
在第 12 章中,他让您定义了一个关联对象 Follow,其中包含关注者和被关注者,两者都映射到用户,以及添加关注者和关注到 Users 类。
我原来是把关联表放在User表之后,运行python manage.py db upgrade时报错:
line 75, in User followed = db.relationship('Follow', foreign_keys= [Follow.follower_id],
NameError: name 'Follow' is not defined
然后我将关联对象 class Follow 移到 class User 定义之上,然后重新运行迁移。这次成功了。
有人能解释一下原因吗?
两个类定义似乎都需要另一个。
我应该知道关于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 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')
定义顺序:
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)
或者也许顺序根本不重要,而我错误地归咎于问题?
【问题讨论】:
标签: sqlalchemy flask-sqlalchemy