Python Django 模型方法 - create_or_update
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16329946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django model method - create_or_update
提问by snakesNbronies
Similar to get_or_create, I would like to be able to update_or_createin Django.
与 类似get_or_create,我希望能够update_or_create在 Django 中。
Until now, I have using an approaching similar to how @Daniel Roseman does it here. However, I'd like to do this more succinctly as a model method.
到目前为止,我使用的方法类似于@Daniel Roseman 在这里的方法。但是,作为模型方法,我想更简洁地做到这一点。
This snippetis quite old and I was wondering if there is a better way to do this in more recent version of Django.
这段代码很旧,我想知道在更新的 Django 版本中是否有更好的方法来做到这一点。
采纳答案by dbkaplun
See QuerySet.update_or_create(new in Django 1.7dev)
请参阅QuerySet.update_or_create(Django 1.7dev 中的新功能)
回答by suhailvs
There is update_or_create, eg::
有update_or_create,例如::
obj, created = Person.objects.update_or_create(
first_name='John', last_name='Lennon',
defaults={'first_name': 'Bob'},
)
# If person exists with first_name='John' & last_name='Lennon' then update first_name='Bob'
# Else create new person with first_name='Bob' & last_name='Lennon'

