Flask + SQLAlchemy adjacency list backref error Flask + SQLAlchemy adjacency list backref error flask flask

Flask + SQLAlchemy adjacency list backref error


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.


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

from sqlalchemy.orm import backref