Flask + SQLAlchemy邻接列表backref错误

时间:2014-10-20 22:27:51

标签: 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

我做错了什么?

2 个答案:

答案 0 :(得分:8)

在这一行......

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=backref,您需要backref=db.backref

答案 1 :(得分:0)

您必须明确说明什么是backref。您可以通过以下导入操作做到这一点:

from sqlalchemy.orm import backref
相关问题