我有以下模型:
class Category(db.Model):
__tablename__ = 'categories'
id = db.Column(db.Integer, primary_key=True)
parent_id = db.Column(db.Integer, db.ForeignKey(id), nullable=True)
level = db.Column(db.SmallInteger)
name = db.Column(db.String(200))
children = db.relationship('Category', backref=backref('parent', remote_side=id))
def __repr__(self):
return '<Category %r>' % (self.name)
这似乎行不通。我总是收到以下错误:
NameError: name 'backref' is not defined
我做错了什么?
最佳答案
在这条线上...
children = db.relationship('Category', backref=backref('parent', remote_side=id))
您正在使用属性 backref
,但从未定义它。如果你写了...,你会得到类似的错误。
children = db.relationship('Category', backref=photosynthesis('parent', remote_side=id))
同样的问题:Python 不知道“光合作用”是什么。
那么,backref 实际上应该在您的代码中是什么?结果是 function that is part of SQLAlchemy .与其中许多函数(例如,您正在使用的“关系”函数)一样,Flask-SQLAlchemy 将为您提供一个别名,因此您无需直接导入它们。
您可以使用 docs作为你的向导。您需要 backref=db.backref
而不是 backref=backref
。
关于python - Flask + SQLAlchemy 邻接表 backref 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475977/