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?
I pretty sure there won’t be any decently performing way to do this in pure Python until many-to-many prefetching gets implemented in 1.4
In the meantime, this is how I’d do it by dropping down into SQL:
Of course, the simpler way would simply be to refactor your code to operate on two separate querysets: