更新django模型对象的单个字段的简洁方法

时间:2021-07-23 20:23:54

To update (and save) the field on an object you do:

更新(并保存)对象上的字段:

>>> product = Product.objects.get(name='Venezuelan Beaver Cheese')
>>> product.number_sold = 4
>>> product.save()

Is there a way to compress the last two lines into a single line, like:

有没有办法把最后两行压缩成一行,比如:

product.update(number_sold=4)

3 个解决方案

#1


22  

Yup.

是的。

Product.objects.filter(name='Venezuelan Beaver Cheese').update(number_sold=4)

If you have a model instance you changed and want to save only specific fields to the database, do that:

如果您更改了一个模型实例,并且只希望将特定字段保存到数据库中,请这样做:

product.name = "New name of the product"
product.save(update_fields=['name'])

#2


6  

@Lovelive's answer is the best way to go. The only downside is that you don't get the instance with that. So you still need the product = Product.objects.get(...) line if you need product for anything else. However, it does cover the use-case scenario of "compress the last two lines into a single line" perfectly.

@Lovelive的回答是最好的选择。唯一的缺点是你无法获得实例。因此,如果您需要其他产品,仍然需要product = product .objects.get(…)行。但是,它确实覆盖了“将最后两行压缩成一行”的用例场景。

Just to play devil's advocate, you could also add a method to your model:

你也可以在你的模型中添加一个方法:

class Product(models.Model):
    ...
    def update(self, **kwargs):
        for k, v in kwargs.iteritems():
            setattr(self, k, v)
        self.save()

#3


0  

Depending on the situation this is also an alternative:

视情况而定,这也是一个备选办法:

product.save(update_fields=["number_sold"])

#1


22  

Yup.

是的。

Product.objects.filter(name='Venezuelan Beaver Cheese').update(number_sold=4)

If you have a model instance you changed and want to save only specific fields to the database, do that:

如果您更改了一个模型实例,并且只希望将特定字段保存到数据库中,请这样做:

product.name = "New name of the product"
product.save(update_fields=['name'])

#2


6  

@Lovelive's answer is the best way to go. The only downside is that you don't get the instance with that. So you still need the product = Product.objects.get(...) line if you need product for anything else. However, it does cover the use-case scenario of "compress the last two lines into a single line" perfectly.

@Lovelive的回答是最好的选择。唯一的缺点是你无法获得实例。因此,如果您需要其他产品,仍然需要product = product .objects.get(…)行。但是,它确实覆盖了“将最后两行压缩成一行”的用例场景。

Just to play devil's advocate, you could also add a method to your model:

你也可以在你的模型中添加一个方法:

class Product(models.Model):
    ...
    def update(self, **kwargs):
        for k, v in kwargs.iteritems():
            setattr(self, k, v)
        self.save()

#3


0  

Depending on the situation this is also an alternative:

视情况而定,这也是一个备选办法:

product.save(update_fields=["number_sold"])