porton
porton

Reputation: 5803

Existence of an object in many-to-many relation

Python Django code:

class UserGroup(models.Model):
    users = models.ManyToManyField(User)

    def __contains__(user):
        pass # What should be here?

(User here is another model.)

How to efficiently check whether a user "belongs" to the given group of users?

Upvotes: 1

Views: 29

Answers (1)

Ivan Semochkin
Ivan Semochkin

Reputation: 8897

You can check it by m2m manager:

def __contains__(self, user):
    return user in self.users.all() # return boolean

Now just check it with your instances:

user = User.objects.get(pk=some_pk) 
group = UserGroup.objects.get(pk=some_pk)
# or use another queries to fetch instanses
if user in group:
    # do your logic

Upvotes: 1

Related Questions