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?
You can try
A.objects.filter(members__id=1).exists()
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:
results = A.objects.all().extra(
select={
'has_object': 'EXISTS(SELECT * FROM myapp_a_members WHERE a_id=myapp_a.id AND b_id=1)'
}
)
Of course, the simpler way would simply be to refactor your code to operate on two separate querysets:
results_with_member_1 = A.objects.filter(members__id=1)
results_without_member_1 = A.objects.exclude(members__id=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With