为什么我不能在Django中保存一个对象? [英] 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!
我进入我的数据库,我运行一个简单的SELECT语句,它没有改变!
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;
推荐答案
这里发生的是Score.objects.filter ()不返回常规列表,而是 QuerySet 。 QuerySets在某些方面表现得像列表一样,但是每次切片时您都可以获得一个新的QuerySet实例,并且每次索引到一个时,都会得到一个新的模型类实例。
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
如果无论什么原因,在QuerySet上执行此操作,而不仅仅是使用get(),您可以写:
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()
而不是。如果你说的是迭代QuerySet的元素而不是处理单个记录,这个区别就更重要了。
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.
这篇关于为什么我不能在Django中保存一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!