Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 588
int3 Avatar asked Dec 11 '11 03:12

int3


2 Answers

You can try

A.objects.filter(members__id=1).exists()
like image 154
szaman Avatar answered Nov 15 '22 09:11

szaman


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)
like image 29
Evan Brumley Avatar answered Nov 15 '22 08:11

Evan Brumley