python - Flask + SQLAlchemy 邻接表 backref 错误

标签 python orm flask sqlalchemy 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)

这似乎行不通。我总是收到以下错误:

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/

相关文章:

Hibernate 3.6 - session.get() 与 session.load()

python - 如何将数据放入 PyPi python 包中并通过 pip 检索?

python - 子进程打开以运行命令(HDFS/hadoop)

python - 从 ORM 中提取数据并按日期分组

grails - 有关在Grails中实现域类关系和约束的问题

javascript - Flask - 我想要一种基于数据库数据显示任务流程图的方法

python - 不同平台上按钮的顺序(QDialogBu​​ttonBox)

python - 使用 Tweepy 访问 twitter API 时出错

python - Flask、Postman 和 Mysql 多字段插入问题

python - 使用基于类的 View 管理 Flask 中可选的动态 URL 段