Edward Black
Edward Black

Reputation: 250

Django model instance from queryset not updating on save()

I have the following code

VocabFromDatabase = Vocab.objects.filter(User = U, IsCard = True).order_by("LastStudyDate")
VocabFromDatabase[0].Mnem = "Passed"
VocabFromDatabase[0].save()

According the docs save() should save the changes, but it seems to silently fail. After some fiddling around it seems the problem isn't with save() but rather with assigning a value to a property of one of the objects from the queryset. However everywhere I look tells me to either use update() (which I think would update all the objects in the queryset, which I do not want), or that save() should work.

Is there something I'm not aware of, or something I'm doing wrong here?

Upvotes: 1

Views: 1297

Answers (1)

Jason Lim
Jason Lim

Reputation: 26

Looks like setting the model's name field and calling the model's save method is being done to 2 separate references of the model. Everytime you select via [index], queryset is returning from its cache.

https://docs.djangoproject.com/en/2.1/topics/db/queries/#when-querysets-are-not-cached

queryset[0].name = "foo" // <Model pk=1 name="foo">
queryset[0].save() // <Model pk=1 name=default> SAVED

Upvotes: 1

Related Questions