KRT*_*Tac 3 python orm sqlalchemy flask flask-sqlalchemy
我有以下型号:
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)
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用.我总是得到以下错误:
NameError: name 'backref' is not defined
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
在这条线上......
children = db.relationship('Category', backref=backref('parent', remote_side=id))
Run Code Online (Sandbox Code Playgroud)
您正在使用该属性backref,但从未定义过它.如果你写了......你会得到类似的错误
children = db.relationship('Category', backref=photosynthesis('parent', remote_side=id))
Run Code Online (Sandbox Code Playgroud)
同样的问题:Python不知道"光合作用"是什么.
那么,什么是backref实际上应该在你的代码中呢?原来它是SQLAlchemy的一部分功能.与许多这些函数(例如,您正在使用的"关系"函数)一样,Flask-SQLAlchemy将为您提供别名,因此您无需直接导入它们.
您可以使用文档作为指南.而不是backref=backref,你想要的backref=db.backref.
| 归档时间: |
|
| 查看次数: |
1013 次 |
| 最近记录: |