Django ORM中使用update_or_create功能

https://www.cnblogs.com/aguncn/p/4922654.html

今天,看了看官方文档,关于这个update_or_create,有了新的作法。

原理,就是filter条件照写,但使用一个defaults 字典来来决定是新增还是更新。

我自己的写代码片断如下:

defaults = dict()
defaults['name'] = '{}-{}-yaml'.format(app, env)
defaults['content'] = yaml_content
AppEnvYamlOnline.objects.update_or_create(app=app,
                                              env=env,
                                              defaults=defaults,)

 

官网的手写版如下:

复制代码
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()
复制代码

 

官网的更新版如下:

obj, created = Person.objects.update_or_create(
    first_name='John', last_name='Lennon',
    defaults={'first_name': 'Bob'},
)

 

posted on 2019-03-12 17:50  人之初-柳  阅读(6931)  评论(0编辑  收藏  举报