On 16 heinä, 14:38, Sithembewena Lloyd Dube <zebr...@gmail.com> wrote: > Hi everyone, > > 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)
Querysets are always cloned on calling a method, so the right syntax is: categories = categories.exclude(pk=cat.pk). For efficiency reasons you might want to collect all the pks into a list, and then after the loop do one: categories = categories.exclude(pk__in=pk_list) The queryset cloning can be expensive if you do a lot of operations. Of course, the annotation way given downthread is likely to be the most effective way to do this. - Anssi -- 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.