check for empty querysets in django

2.2k Views Asked by At

I have a custom manager for my model device. If the queryset that is returned is empty, I want to return a different object. The problem is that an empty queryset is not evaluated as empty.

I looked into these threads for finding out how to check if a queryset is empty. In Django, what is the most efficient way to check for an empty query set? Checking for empty queryset in Django

This is my model:

    class DeviceField(models.Model):
    """
    Can be connected to any class and any field in that class. Specifies how the values and field names are returned for the field.
    """
    device = models.ForeignKey(Device, verbose_name=_("Device"))
    content_type = models.ForeignKey(ContentType, verbose_name=_("Class"))
    field_name = models.CharField(max_length=150, verbose_name=_("field name"))
    display_field = models.CharField(max_length=255, verbose_name=_("How to display the field name?"))
    display_value = models.CharField(max_length=255, verbose_name=_("How to display the value?"))

    objects = DeviceFieldManager()

And this is my manager. See how I use all these if-statements to check if it is empty.

class DeviceFieldManager(models.Manager):
    """
    Behaves like a normal manager. Except in the case that no such device field exists. Then it will return the standard value of the field.
    """
    def get_query_set(self):
        """
        Does the queryset overriding :). If empty, get the original values
        """
        queryset = super(DeviceFieldManager,self).get_query_set()
        try:
            a = queryset[0]
            print "we have something here"
        except IndexError:
            print "It is frigging empty"
        if queryset == super(DeviceFieldManager, self).none():
            print "this queryset is just like an empty one"
        if not queryset:
            print "not queryset"
        if not queryset.count():
            print "not queryset count"
        if queryset:
            print "if queryset"
        if queryset.exists():
            print "queryset exists"
        else:
            print "A value is return, we don't need to do anything!"
        print queryset.count()
        print super(DeviceFieldManager, self).none()
        print queryset == super(DeviceFieldManager, self).none()
        return queryset

And this is from the shell. For the devices "mobile" (which exists) and "cow" (which does not exist) the Manager shows the same behaviour. When I try to print the first value of the queryset, I get the expected IndexError for "cow".

In [8]: a= DeviceField.objects.filter(device__name="mobile")
we have something here
if queryset
queryset exists
1
[]
False

In [9]: a[0]
Out[9]: <DeviceField: DeviceField object>

In [10]: a= DeviceField.objects.filter(device__name="cow")
we have something here
if queryset
queryset exists
1
[]
False

In [11]: a[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/<ipython-input-11-5ccf417d7af1> in <module>()
----> 1 a[0]

/local/lib/python2.7/site-packages/django/db/models/query.pyc in __getitem__(self, k)
    188             qs = self._clone()
    189             qs.query.set_limits(k, k + 1)
--> 190             return list(qs)[0]
    191         except self.model.DoesNotExist, e:
    192             raise IndexError(e.args)

IndexError: list index out of range

What am I doing wrong here? How I can I check in the manager if the queryset is empty or not?

Thanks a lot :)

1

There are 1 best solutions below

0
On

Manager's get_query_set is called before filtering so you'll need to hack somehow into QuerySet itself (or make external function which will do checking).