Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy backref function and backref parameter

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', lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

But then there is also a backref function:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address',
                                backref=db.backref('person', lazy='joined'), 
                                lazy='dynamic')

In this case, what's the role of the backref function passed to the backref parameter, especially with the multiple lazy definitions? How is it different from backref='person'?

like image 565
kentwait Avatar asked Jun 14 '17 08:06

kentwait


People also ask

What does Backref do in SQLAlchemy?

backref keyword argument on the relationship() construct allows the automatic generation of a new relationship() that will be automatically be added to the ORM mapping for the related class. It will then be placed into a relationship.

What is back populate in SQLAlchemy?

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.

How do I create a many to many relationship in SQLAlchemy?

Many to Many relationship between two tables is achieved by adding an association table such that it has two foreign keys - one from each table's primary key.


1 Answers

From the documentation for Flask models:

backref is a simple way to also declare a new property on the Address class. You can then also use my_address.person to get to the person at that address. lazy defines when SQLAlchemy will load the data from the database:

select (which is the default) means that SQLAlchemy will load the data as necessary in one go using a standard select statement.

joined tells SQLAlchemy to load the relationship in the same query as the parent using a JOIN statement.

subquery works like 'joined' but instead, SQLAlchemy will use a subquery.

dynamic is special and useful if you have many items. Instead of loading the items SQLAlchemy will return another query object which you can further refine before loading the items. This is usually what you want if you expect more than a handful of items for this relationship.

like image 73
Ricky Han Avatar answered Oct 13 '22 00:10

Ricky Han