What does backref mean in relation tables Many to Many in Sqlalchemy?

Asked

Viewed 147 times

0

I am creating a database template in my models.py for my Flask application. I have a User table, and each user can have multiple instruments, and one instrument can have multiple users.

In the documentation of Sqlalchemy and of Flask-Sqlalchemy they recommend creating a table and not a template as it is created for user to stop support this relationship, I did as the documentation recommends, but still not understood what refers to the parameter backref.

usuario_instrumento = db.Table('usuario_instrumento',
    db.Column('instrumento_id', db.Integer, db.ForeignKey('instrumento.id'), primary_key=True),
    db.Column('usuario_id', db.Integer, db.ForeignKey('usuario.id'), primary_key=True)
)

class Usuario(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    instrumentos = db.relationship('Instrumento', secondary=usuario_instrumento, lazy='subquery',
        backref=db.backref('usuarios', lazy=True))

class Instrumento(db.Model):
    id = db.Column(db.Integer, primary_key=True)

1 answer

0

You can understand the attribute backref as being an attribute in the table that you specified as the other part of the relationship, in your case is the table Instrumento.

It becomes very useful when making querys in the relationship, because from this statement, you can make a query like Instrumento.usuarios, to know which users are associated with a particular instrument.

Note that this relationship can be done in either of the two tables, it will depend only on what makes the most sense for your use case. If you want to do the reverse query, (Usuario.instrumentos), to know which users are associated with a particular element, simply add the same attribute type in the Instrument table:

usuarios = db.relationship('Usuario', secondary=usuario_instrumento, lazy='subquery',
        backref=db.backref('instrumentos', lazy=True))

I hope I have helped and good learning!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.