我如何在同一个查询集上运行更新和选择语句,而不是必须进行两次查询: - 1选择对象 -一个用于更新对象

在SQL中等价的东西是这样的:

update my_table set field_1 = 'some value' where pk_field = some_value

当前回答

这个答案比较了上述两种方法。 如果你想在一行中更新多个对象,请执行:

# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')

否则你将不得不遍历查询集并更新单个对象:

#Approach 2    
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
    obj.field2 = 'cool'
    obj.save()

Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes 'n+1' database queries. (For n items in the query set) Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE. The tradeoff is that, suppose you have any triggers, like updating updated_on or any such related fields, it will not be triggered on direct update ie approach 1. Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.

其他回答

使用queryset对象更新方法:

MyModel.objects.filter(pk=some_value).update(field1='some value')

Django数据库对象使用相同的save()方法来创建和更改对象。

obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()

Django如何知道UPDATE和INSERT 如果对象的主键属性被设置为一个值,该值的值为True(即,一个值 除了None或者空字符串),Django执行一个UPDATE。如果 对象的主键属性没有设置,或者UPDATE没有设置 更新任何东西,Django执行INSERT。

Ref。https://docs.djangoproject.com/en/1.9/ref/models/instances/

这个答案比较了上述两种方法。 如果你想在一行中更新多个对象,请执行:

# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')

否则你将不得不遍历查询集并更新单个对象:

#Approach 2    
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
    obj.field2 = 'cool'
    obj.save()

Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes 'n+1' database queries. (For n items in the query set) Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE. The tradeoff is that, suppose you have any triggers, like updating updated_on or any such related fields, it will not be triggered on direct update ie approach 1. Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.

1号方法

MyTable.objects.filter(pk=some_value).update(field1='some value')

2方法

q = MyModel.objects.get(pk=some_value)
q.field1 = 'some value'
q.save()

第三个方法

通过使用get_object_or_404

q = get_object_or_404(MyModel,pk=some_value)
q.field1 = 'some value'
q.save()

4日法

如果pk=some_value存在,则更新它,使用update_or_create创建一个新的。

MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})

如果你需要基于旧字段值设置新值,那就像这样做:

update my_table set field_1 = field_1 + 1 where pk_field = some_value

使用查询表达式:

MyModel.objects.filter(pk=some_value).update(field1=F('field1') + 1)

这将自动执行更新,即对数据库使用一个更新请求,而不首先读取它。