Bert Davies Bert Davies - 12 days ago 5
Python Question

django filter and order by not being able to modify field?

I have a BooleanField called 'used' in my LabHours model which has a default value of False (this is supposed to be an attendance system), and I want to set this to True based on a filter and ordering. Even though I explicitly set this field to be true, when I print out its value, it still displays False.

Here is my code for reference:

LabHours.objects.filter(used=False).order_by("endtime").first().used = True
for hours in LabHours.objects.all():
hours.save()
print hours.used


Console output:

False
False
False
False
False
False
False


Why does it not set this field to be True?

wim wim
Answer

The change in the first line of your code goes unsaved, and then you're just looping through the queryset and triggering save on model instances with no changes.

You'll need to call save using the model instance on which you mutated state:

obj = LabHours.objects.filter(used=False).order_by("endtime").first()
obj.used = True
obj.save()
Comments