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?
In Flask-SQLAlchemy, the backref parameter in relationship method allows you to declare a new property under a specified class as seen in the example in their docs: class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) addresses = db.relationship('Address', backref='person ...
The back_populates argument tells SqlAlchemy which column to link with when it joins the two tables. It allows you to access the linked records as a list with something like Parent.
Step 1 - Install the Flask-SQLAlchemy extension. Step 2 - You need to import the SQLAlchemy class from this module. Step 3 - Now create a Flask application object and set the URI for the database to use. Step 4 - then use the application object as a parameter to create an object of class SQLAlchemy.
Flask-SQLAlchemy is a Flask extension that makes using SQLAlchemy with Flask easier, providing you tools and methods to interact with your database in your Flask applications through SQLAlchemy. In this tutorial, you'll build a small student management system that demonstrates how to use the Flask-SQLAlchemy extension.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With