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'},
)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM