Checking for object’s existence in ManyToMany relation (Django)

djangodjango-models

I'd like to check for a particular object's existence within a ManyToMany relation. For instance:

class A(models.Model):
    members = models.ManyToManyField(B)

class B(models.Model):
    pass

results = [some query]

for r in results:
    print r.has_object // True if object is related to some B of pk=1

My first stab at [some query] was A.objects.all().annotate(Count(has_object='members__id=1')) but it looks like I can't put anything more than the field name into the argument to Count. Is there some other way to do this?

Best Answer

You can try

A.objects.filter(members__id=1).exists()
Related Topic