Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange issue when trying to set a BooleanField value in a django model

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?

like image 305
hora Avatar asked Feb 27 '23 15:02

hora


1 Answers

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.

like image 195
Daniel Roseman Avatar answered Mar 01 '23 05:03

Daniel Roseman