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?
views:
21answers:
1
+1
A:
Use annotations.
from django.db.models import Count
A.objects.annotate(b_count=Count('b')).filter(b_count__gte=n)
Daniel Roseman
2010-06-23 14:43:25
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
2010-06-23 14:47:43
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
2010-06-23 15:00:21