Sigils
Sigils

Reputation: 2572

Select many to many with Flask-SQLAlchemy

I am trying to SELECT some data from the database with Flask-SQLAlchemy. However, I am struggling getting the right data and joining with many-to-many.

My models looks like this.

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_firstName = db.Column(db.String(64))
    ...
    role_id = db.Column(db.Integer, db.ForeignKey('role.role_id'))


class Role(db.Model):
    role_id = db.Column(db.Integer, primary_key=True)
    role_name = db.Column(db.String(64), unique=True)
    users = db.relationship('User', backref='role')

and then the table I want to get with many to many
note using backref

class Class(db.Model):
    class_id = db.Column(db.Integer, primary_key=True)
    class_name = db.Column(db.String(128), unique=True)
    mm_children = db.relationship('User', secondary=student_identifier, backref=db.backref('classes'))

and here is the table which holds the many-to-many information (the link between user and class)

student_identifier = db.Table('student_identifier',
    db.Column('class_id', db.Integer, db.ForeignKey('class.class_id')),
    db.Column('id', db.Integer, db.ForeignKey('user.id'))
)

lets say I have this in my database

User
id          user_firstName  role_id
1           'John'          3
2           'Jane'          3
3           'Jack'          1
4           'Jimmy'         3
5           'Jana'          2


Role
role_id     role_name
1           'Admin'
2           'Teacher'
3           Student'


Class
class_id    class_name
1           'A'
2           'B'
3           'C'

student_identfier
class_id    id
1           1
1           2
2           2
3           1
1           4

student_identfier
class_id        id
1               1
1               2
2               2
3               1
1               4

then if you want to loop all the ones with class id 1 and 2. And get their names

id      class_name   role_name
1       'A'          'Student'
2       'A'          'Student'

2       'B'          'Student'



EDIT
I managed to get the classes, but without the in clause.

db.session.query(
    User.user_fistName,
    Role.role_name,
    Class.class_name
).join(Role).filter_by(role_name='Student').filter(User.classes)

Upvotes: 1

Views: 661

Answers (1)

TNT
TNT

Reputation: 3620

If your models and relations work, you should be able to do something like this:

users = session.query(User).all()
for user in users:
    users_classes = ','.join([c.class_name for c in user.classes])
    print("{0} is {1} in {2}".format(user.user_firstName,
                                     user.role.role_name,
                                     users_classes))

Hope this helps.

Upvotes: 1

Related Questions