Django model method - create_or_update

久未见 提交于 2020-05-25 06:09:20

问题


Similar to get_or_create, I would like to be able to update_or_create in 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.

This snippet is quite old and I was wondering if there is a better way to do this in more recent version of Django.


回答1:


See QuerySet.update_or_create (new in Django 1.7dev)




回答2:


There is update_or_create, eg::

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'


来源:https://stackoverflow.com/questions/16329946/django-model-method-create-or-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!