views:

21

answers:

1

For instance, given a model A, and a model B, where A are unique records, and B are records that have Foreign Keys to A, how would you go about getting a set of A where those in the set are referenced by B at least n or more times?

+1  A: 

Use annotations.

from django.db.models import Count
A.objects.annotate(b_count=Count('b')).filter(b_count__gte=n)
Daniel Roseman
Interesting, how will will this perform? I suppose I can always get the raw sql from this and run the showplan on it in the DBMS. Are there other ways to do this in Django that are more/less optimal? Just curious.
Leeks and Leaks
This is as efficient as it gets: it'll do a GROUP BY/HAVING query in the db. The only other way to do it would be to grab all the B objects related to A and count them in Python - orders of magnitude more expensive, I'd expect.
Daniel Roseman