tags:

views:

23

answers:

2

How can I count related objects in Django (in less than N queries, where N is number of object).

To clarify, let's say I have tables A and B. Every B is connected to exactly one A. Approach I tried:

A.objects.select_related().filter(attr=val)
A[i].B_set.count()

Of course, for every A[i] I want to find out number of B objects Django executes one query.

So the question is - is there a way to optimize that?

A: 

Have not tried how many queries are executed, but the djano way should be using annotate() something like:

q = A.objects.select_related().annotate(num_B=Count('B'))
print A[0].num_B
lazerscience
A: 

I have to answer my own question :) If object of A is queried something like this:

A.objects.select_related().filter(atrr=val).annotate(n_b=models.Count('B'))

This creates very long query, but at least there is just one.

EDIT: Shit, just answered, thnx...

ivan