I'm trying to change the value of a BooleanField in one of my models, but Django won't let me. Here's the relevant code:
query = MyModel.objects.filter(name='example').filter(boolField=False)
print query[0].boolField
query[0].boolField = True
query[0].save()
print query[0].boolField
This surprisingly prints:
False
False
Any idea why the = True
isn't sticking? Thanks in advance!
Edit: This fixed it:
query = MyModel.objects.get(name='example', boolField=False)
query.boolField = True
query.save()
It seems you can't change fields in a query that you filtered by?
It's not the filtering that's the problem, it's the slicing. Each time you slice a queryset, Django gives you a different object:
f = MyModel.objects.all()[0]
f.id # 1
id(f) # 4326035152
ff = MyModel.objects.all()[0]
ff.id # 1
id(ff) # 4326035344
Here f
and ff
refer to the same underlying database row, but different actual object instances. So in your example, the instance you set the boolean on is not the same as the instance you tried to save.
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