views:

84

answers:

2
thechan = Score.objects.filter(content=44)[0:1]
thechan[0].custom_score = 2
thechan[0].save()

I do print statements, and it shows everything fine. However, it's not SAVING!

I go into my database, and I run a simple SELECT statement..and it's not changed!

select custom_score FROM music_score where content_id = 44;
A: 

Fixed.

thechan = Score.objects.get(content=44)
thechan.custom_score = 2
thechan.save()
TIMEX
Uh... what? How is that code working?
harto
2 warnings: Django will raise for you: "MultipleObjectsReturned: get() returned more than one Score" and, if more than 1 "content", will raise Object.DoesNotExist if no results.
panchicore
+10  A: 

What's going on here is that Score.objects.filter() doesn't return a regular list, but a QuerySet. QuerySets behave like lists in some ways, but every time you slice one you get a new QuerySet instance, and everytime you index into one, you get a new instance of your model class.

That means your original code does something like:

thechan = Score.objects.filter(content=44)[0:1]
thechan[0].custom_score = 2

thechan = Score.objects.filter(content=44)[0:1]
thechan[0].save() # saves an unmodified object back to the DB, no effective change

If for whatever reason you needed to do this on a QuerySet rather than just using get(), you could write:

thechan = Score.objects.filter(content=44)[0]
thechan.custom_score = 2
thechan.save()

instead. This distinction becomes a bit more important if you are, say, iterating over the elements of a QuerySet instead of dealing with a single record.

David Winslow