Search code examples
djangodjango-modelsmodelmany-to-many

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?


Solution

  • 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