Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django QuerySet: Is it possible to filter for field__is_null for FloatFields?

I want to be able to query a model for records where the is no value for a particular float field. The problem is the basic query:

 Model.objects.filter(float_field__is_null=True)

returns the following error: django.core.exceptions.FieldError: Unsupported lookup 'is_null'.

To test, create the following model:

class FloatFieldModel(models.Model):
    date = models.DateField()
    val = models.FloatField(blank=True, null=True)

Then:

>>> objects = FloatFieldModel.objects.filter(val__is_null=True)
>>> django.core.exceptions.FieldError: Unsupported lookup 'is_null' ...

How can I filter a model for records where there is no value for a particular float field? In other words, what is the best work around?

What I want to be able to do is the set up a routine to only update rows without any values, but skip those rows already with a specified value (while making most efficient use of my database). What I was trying looks something like:

for date in dates:
    try:
        FloatFieldModel.objects.filter(
            date=date,
            val__is_null=True
        ).update(val=42.0)
    except FloatFieldModel.DoesNotExist:
        pass

I imagine I could do something like:

objects = FloatFieldModel.objects.all()
for obj in objects:
    if obj.val is None and obj.date in set(dates):
        obj.val = 42.0
        obj.save()

I was trying for a more efficient process though, rather than on which required reading each object from the database into memory before saving.

like image 425
Cole Avatar asked Nov 18 '14 19:11

Cole


1 Answers

There is lookup isnull not is_null https://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-isnull

Model.objects.filter(float_field__isnull=True)
like image 123
madzohan Avatar answered Nov 12 '22 03:11

madzohan