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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With