5
votes

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?

2

2 Answers

10
votes

On this line...

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

You are using the attribute backref, but have never defined it. 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.

So, what is backref actually supposed to be in your code? Turns out it's a function that is part of SQLAlchemy. Like many of these functions (e.g., the "relationship" function you are using), Flask-SQLAlchemy will provide to you an alias so you don't need to import them directly.

You can use the docs as your guide. Instead of backref=backref, you want backref=db.backref.

3
votes

You have to explicit what backref is. You can do it with this import:

from sqlalchemy.orm import backref