Django-更新模型对象

Django- Update Model objects

我有一个模型:-

class Model(models.Model):
    a = models.BooleanField(default=False)
    time = models.DateTimeField(auto_now_add=True)

触发 all 查询后:-

objs = Model.objects.all().order_by('time')

我需要更新 nth 索引处的对象。 N可以是任何东西。

obj[0].a = True
obj[0].save()

但是值没有更新。为什么?

def set_nth_a_true(n, queryset):
   obj_ = queryset[n]
   obj_.a = True
   obj_.save()


objs = Model.objects.all().order_by('time')
set_nth_a_true(3, objs)

这应该可以,我测试过

objs = Model.objects.all()
objs[0].a = True  # Queries the database
objs[0].save()  # And again queries db before save

更多信息为什么会发生在文档中:

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

我刚刚 运行 遇到了同样的问题,我可以确认 "issue" 与 QuerySets 行为有关。如果您需要更新您的对象,您必须将它们存储为单独的模型对象,例如:

objs = Model.objects.all().order_by('time')
to_update = objs[0]
to_update.a = True
to_update.save()