Django ORM 的 update_or_create

Django ORM 的 update_or_create

官网的手写版如下:

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'},
)
发布了44 篇原创文章 · 获赞 0 · 访问量 3939

猜你喜欢

转载自blog.csdn.net/cpxsxn/article/details/102964452