Django模型方法 - create_or_update

sna*_*ies 12 python django django-models django-orm

类似于get_or_create,我希望能够update_or_create在Django.

到目前为止,我已经使用了类似于@Daniel Roseman在这里做到的方式.但是,我想更简洁地将其作为一种模型方法.

这个片段很老了,我想知道在更新版本的Django中是否有更好的方法可以做到这一点.

suh*_*lvs 42

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'
Run Code Online (Sandbox Code Playgroud)

  • 感谢您解释默认值的作用。文档中非常混乱。:D (7认同)
  • @ShahriarRahmanZahin 谢谢你的客气话。也许我会在 django 中提交拉取请求\ (3认同)
  • 迄今为止我见过的关于“默认值”作用的最佳解释。文档中不清楚。 (2认同)

dbk*_*lun 15

请参阅QuerySet.update_or_create(Django 1.7dev中的新增内容)