On Mon, Jul 16, 2012 at 01:38:47PM +0200, Sithembewena Lloyd Dube wrote:
I have a queryset of categories and would like to exclude categories with
no items associated. I am cycling through the queryset as follows, without
the desired result:
for cat in categories:
if cat.item_set.count() == 0:
categories.exclude(pk=cat.pk)
How can I remove those categories (please note, I do not intend to delete
them)?
You can use an annotation:
categories.objects.annotate(Count(item)).exclude(item__count=0)
What this does is add a temporary attribute on each category
object named `item__count', then you can exclude based on that
attribute.
https://docs.djangoproject.com/en/1.4/ref/models/querysets/#annotate
me
--
You received this message because you are subscribed to the Google Groups "Django
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.