Bert Davies Bert Davies - 1 year ago 114
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():
print hours.used

Console output:


Why does it not set this field to be True?

wim wim
Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download