Flags list + SQLAlchemy adjacency backref

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 does not work. I always get the following error:

NameError: name 'backref' is not defined

      

What am I doing wrong?

+3


source to share


2 answers


In this line ...

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

      

You are using an attribute backref

, but you have never defined it. You would get a similar error if you wrote ...

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

      



Same problem: Python doesn't know what "photosynthesis" is.

So what is the backref actually supposed to be in your code? It turns out that this is a function that is part of SQLAlchemy . Like many of these functions (for example the "relationship" function used), Flask-SQLAlchemy will provide you with an alias, so you don't need to import them directly.

You can use the docs as a guide . Instead backref=backref

you want backref=db.backref

.

+8


source


You must explicitly state what a backlink is. You can do it with this import:



from sqlalchemy.orm import backref

      

0


source







All Articles