Django ORM中使用update_or_create功能

官网的手写版如下:

update_or_create(defaults=None**kwargs)

A convenience method for updating an object with the given kwargs, creating a new one if necessary. The defaults is a dictionary of (field, value) pairs used to update the object. The values in defaults can be callables.

Returns a tuple of (object, created), where object is the created or updated object and created is a boolean specifying whether a new object was created.

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.

This is meant as a shortcut to boilerplatish code. For example:

大致意思是创建或者更新,当过滤条件匹配到查询结果则将更新defaults字典中的字段,否则创建一条记录,字段内容为defaults字段中的内容。

 返回(对象,已创建)的元组,其中object是已创建或已更新的对象,created是一个布尔值,指定是否创建了新对象。

defaults = {'first_name': 'Bob'}
try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
    for key, value in defaults.items():
        setattr(obj, key, value)
    obj.save()
except Person.DoesNotExist:
    new_values = {'first_name': 'John', 'last_name': 'Lennon'}
    new_values.update(defaults)
    obj = Person(**new_values)
    obj.save()

以上的方法使用update_or_create实现

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)
原文地址:https://www.cnblogs.com/harryblog/p/12034640.html