views:

26

answers:

1

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?

+3  A: 

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.

Daniel Roseman
Ah, thanks. That makes much more sense.
hora