Django model method - create_or_update

后端 未结 2 1292
一整个雨季
一整个雨季 2020-12-31 00:18

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 d

相关标签:
2条回答
  • 2020-12-31 00:23

    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'
    
    0 讨论(0)
  • 2020-12-31 00:37

    See QuerySet.update_or_create (new in Django 1.7dev)

    0 讨论(0)
提交回复
热议问题