[Django]-Django Managers – Retrieving objects with non-empty set of related objects

6👍

First of all according to documentation you cannot use model methods for lookup with filter/exclude clause. Then also you cannot use python operators (> in your case) with filter/exclude.

To resolve your task if you are using Django 1.1beta:

from django.db.models import Count

#...

def get_query_set(self):
    return super(NonEmptyManager,self).get_query_set()\
      .annotate(num_images=Count('images'))\
      .filter(num_images__gt=0)

But this solution has some limitations.

Another way for Django >= 1.0:

def get_query_set(self):
    return super(NonEmptyManager,self).get_query_set()\
      .filter(images__isnull=True)

Leave a comment