1

There are two tables Group and User. users can belong to several groups at the same time.

Group

class Group(db.Model):
       """ Group model """
       __tablename__ = "group"
       id = db.Column(db.Integer, primary_key=True)
       project_id = db.Column(db.Integer, db.ForeignKey("project.id"), nullable=True)
       project = db.relationship("Project", foreign_keys=[project_id])
       active = db.Column(db.Boolean, default=True, index=True)
       name = db.Column(db.String(64), index=True)

User

class User(db.Model, UserMixin):
    """ User model """
    __tablename__ = "user"

    id = db.Column(db.Integer, primary_key=True)   
    email = db.Column(db.String(128), unique=True, index=True)
    email_confirmed = db.Column(db.Boolean, default=False)    
    password = db.Column(db.String(256), nullable=True)
    groups = db.relationship("Group", secondary=user_has_group, lazy="dynamic",
                     backref=db.backref("users", lazy="dynamic"))

There is a code that must display for each group of users.

groups = Group.query.all()
for group in groups:
    users = User.query.filter(group in User.groups).all()

But the code is not running.

Please help me how to get users to each group.

1 Answer 1

1

Your User has a back reference backref=db.backref("users", lazy="dynamic")

So from a Group object, you can use group.users to get the users in a given group, e.g.

groups = Group.query.all()
for group in groups:
    users = group.users
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.