Skip to content Skip to sidebar Skip to footer

Why Can't I Save An Object In Django?

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 i

Solution 1:

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.

Solution 2:

Fixed.

thechan = Score.objects.get(content=44)
thechan.custom_score = 2
thechan.save()

Post a Comment for "Why Can't I Save An Object In Django?"