update_or_create()

update_or_create默认值=无** kwargs

使用给定更新对象的便捷方法,kwargs必要时创建新对象defaults是用于更新对象的(字段,值)对的字典。值中的值defaults可以是callables。

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

update_or_create方法尝试根据给定的数据从数据库中获取对象kwargs如果找到匹配项,则会更新defaults字典中传递的字段 

这意味着作为boilerplatish代码的快捷方式。例如:

 1 defaults = {'first_name': 'Bob'}
 2 try:
 3     obj = Person.objects.get(first_name='John', last_name='Lennon')
 4     for key, value in defaults.items():
 5         setattr(obj, key, value)
 6     obj.save()
 7 except Person.DoesNotExist:
 8     new_values = {'first_name': 'John', 'last_name': 'Lennon'}
 9     new_values.update(defaults)
10     obj = Person(**new_values)
11     obj.save()

随着模型中字段数量的增加,这种模式变得非常笨拙。上面的例子可以update_or_create()像这样重写

1 obj, created = Person.objects.update_or_create(
2     first_name='John', last_name='Lennon',
3     defaults={'first_name': 'Bob'},
4 )
原文地址:https://www.cnblogs.com/zhouziyuan/p/10137495.html