简体   繁体   English

Flask + SQLAlchemy邻接列表backref错误

[英]Flask + SQLAlchemy adjacency list backref error

I have the following model: 我有以下型号:

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)

This doesn't seem to work. 这似乎不起作用。 I always get the following error: 我总是得到以下错误:

NameError: name 'backref' is not defined

What am I doing wrong? 我究竟做错了什么?

On this line... 在这条线上......

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

You are using the attribute backref , but have never defined it. 您正在使用backref属性,但从未定义过它。 You would get a similar error if you had wrote... 如果你写了......你会得到类似的错误

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

Same problem: Python doesn't know what "photosynthesis" is. 同样的问题:Python不知道“光合作用”是什么。

So, what is backref actually supposed to be in your code? 那么,什么是backref实际上应该在你的代码中呢? Turns out it's a function that is part of SQLAlchemy . 原来它是SQLAlchemy的一部分功能 Like many of these functions (eg, the "relationship" function you are using), Flask-SQLAlchemy will provide to you an alias so you don't need to import them directly. 与许多这些函数(例如,您正在使用的“关系”函数)一样,Flask-SQLAlchemy将为您提供别名,因此您无需直接导入它们。

You can use the docs as your guide. 您可以使用文档作为指南。 Instead of backref=backref , you want backref=db.backref . 而不是backref=backref ,你想要backref=db.backref

You have to explicit what backref is. 你必须明确backref是什么。 You can do it with this import: 您可以使用此导入执行此操作:

from sqlalchemy.orm import backref

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM