【问题标题】:Django model method - create_or_updateDjango 模型方法 - create_or_update
【发布时间】:2013-04-26 03:32:12
【问题描述】:

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

到目前为止,我使用的方法类似于@Daniel Roseman does it here。不过,我想更简洁地把它作为一种模型方法。

This snippet 已经很老了,我想知道在更新版本的 Django 中是否有更好的方法来做到这一点。

【问题讨论】:

标签: python django django-models django-orm


【解决方案1】:

参见QuerySet.update_or_create(Django 1.7dev 中的新功能)

【讨论】:

    【解决方案2】:

    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'
    

    【讨论】:

    • 感谢您解释默认值的作用。这在文档中非常令人困惑。 :D
    • @ShahriarRahmanZahin 谢谢你的客气话。也许我会在 django 中提交一个拉取请求\
    • 那太棒了! @suhailvs
    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多