Search code examples
pythongoogle-app-enginegqldatastore

GQL - Select all parents where specific child is not in children


I'd like to have a parent class (Group) where any number of User may join. I want to display all Groups where the User is not already in. How do I model this data and how do I query? Sorry for not providing any code, but I simply have no idea.

Edit: In SQL, this would be done with a User table, a Group table and a GroupUser cross ref table. And querying would go:

select *
from Group
where Group.ID not in
(
 select GroupID
 from GroupUser
 where UserID = @userid
)

Solution

  • Maybe I put my question unclearly, I am obviously new to GAE and my terminology may be wrong. Anyway here is my solution:

    class User(db.Model):
      username = db.StringProperty()
    
    class Group(db.Model):
      users = db.ListProperty(db.Key)
    

    To find a group and join (somewhat simplified):

    groups = db.GqlQuery("SELECT * "
                         "FROM Group")        
    
    for g in groups:                
       if user.key() not in g.users:                    
          group = g
          break
    
    group.users.append(user.key())