How to filter exact many to many

前端 未结 2 805
离开以前
离开以前 2021-01-26 16:07

I have User and Room model in Flask SQLAlchemy. I need to filter if Room exists with users [user1, user2, ...]. Filter must be exact.
Here are my models:



        
2条回答
  •  离开以前
    2021-01-26 16:48

    After two days of research I have a temporary solution.

    -- room_users is the "secondary" table in 
       -- sqlalchemy many to many between User and Room
    select room.name, room_users.room 
        from room_users join room on room_users.room = room.id 
        where room_users.user in (1,2) 
        group by room_users.room having count(*) = 2;
    

    In python it will be something like this:

    # members contains user emails
    members = ['email1@mail.com', 'email2@mail.com']
    db.session.query(Room.name).join(Room.users).filter(
        User.email.in_(members)
    ).group_by(Room.id).having(
        func.count(Room.id) == len(members)
    ).first()
    

提交回复
热议问题