int3
int3

Reputation: 13201

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?

Upvotes: 7

Views: 7469

Answers (2)

Evan Brumley
Evan Brumley

Reputation: 2468

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)

Upvotes: 5

szaman
szaman

Reputation: 6756

You can try

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

Upvotes: 11

Related Questions