D
D
domanskiy2021-01-19 14:01:41
Flask
domanskiy, 2021-01-19 14:01:41

How to query related O2M tables through sqlalchemy ORM?

Flask
Sqlalchemy
Postgresql

There are two tables (users and roles) User and Role in a DB with an O2M relationship. The tables are linked through a third.
How, having a user's email, find out his role, or rather the name of the role.?

roles_users = db.Table('roles_users',
                       db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
                       db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
                       )

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)
    email = db.Column(db.String(100), unique=True)
    roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))

class Role(db.Model, RoleMixin):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
domanskiy, 2021-01-19
@domanskiy

Understood.
The models I had were mistakenly made by M2M

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question