Flask + SQLAlchemy 邻接列表反向引用错误

5 投票
2 回答
2434 浏览
提问于 2025-04-28 16:16

我有一个这样的模型:

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

我哪里做错了呢?

暂无标签

2 个回答

4

你需要明确一下什么是 backref。你可以通过这个导入来实现:

from sqlalchemy.orm import backref
10

在这一行...

children = db.relationship('Category', backref=backref('parent', remote_side=id))

你使用了一个叫做 backref 的属性,但你从来没有定义过它。如果你写了...

children = db.relationship('Category', backref=photosynthesis('parent', remote_side=id))

同样的问题:Python 不知道“光合作用”是什么。

那么,backref 在你的代码中到底应该是什么呢?其实它是一个属于 SQLAlchemy 的函数。就像你正在使用的“relationship”函数一样,Flask-SQLAlchemy 会给你提供一个别名,这样你就不需要直接导入它们。

你可以参考 文档 来指导你。你应该用 backref=db.backref 来替代 backref=backref

撰写回答