Python django,属性更新模型实例

Python django,属性更新模型实例,python,django,django-models,django-queryset,Python,Django,Django Models,Django Queryset,我发现#3有时不可靠。 在我运行#3之后,有时foo没有正确设置(没有提交?) 当我不想运行信号处理程序时,我通常使用#3 何时使用上述三种方法?如果您只是更新记录,而不需要对模型对象执行任何操作,最有效的方法是调用update(),而不是将模型对象加载到内存中。例如,不要这样做: 1. instance.save() 2. instance.foo = foo; instance.save(update_fields=['foo']) 3. InstanceClass.objects.fi

我发现#3有时不可靠。
在我运行#3之后,有时foo没有正确设置(没有提交?)

当我不想运行信号处理程序时,我通常使用#3


何时使用上述三种方法?

如果您只是更新记录,而不需要对模型对象执行任何操作,最有效的方法是调用
update()
,而不是将模型对象加载到内存中。例如,不要这样做:

1. instance.save()

2. instance.foo = foo; instance.save(update_fields=['foo'])

3. InstanceClass.objects.filter(id=instance.id).update(foo=foo)
这样做:

instance = Entry.objects.get(id=10)
instance.comments_on = False
instance.save()
NB:

  • 使用
    update()*
  • update()
    在SQL级别执行更新,因此不会调用任何
    save()
    ,因此如果您有一个重写的save()方法,您必须使用
    get()
    save()
    的第一种方法
  • 检查文档,这里都有解释

    Entry.objects.filter(id=10).update(comments_on=False)