zoukankan      html  css  js  c++  java
  • Django ORM中使用update_or_create功能

    官网的手写版如下:

    update_or_create(defaults=None**kwargs)

    A convenience method for updating an object with the given kwargs, creating a new one if necessary. The defaults is a dictionary of (field, value) pairs used to update the object. The values in defaults can be callables.

    Returns a tuple of (object, created), where object is the created or updated object and created is a boolean specifying whether a new object was created.

    The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.

    This is meant as a shortcut to boilerplatish code. For example:

    大致意思是创建或者更新,当过滤条件匹配到查询结果则将更新defaults字典中的字段,否则创建一条记录,字段内容为defaults字段中的内容。

     返回(对象,已创建)的元组,其中object是已创建或已更新的对象,created是一个布尔值,指定是否创建了新对象。

    defaults = {'first_name': 'Bob'}
    try:
        obj = Person.objects.get(first_name='John', last_name='Lennon')
        for key, value in defaults.items():
            setattr(obj, key, value)
        obj.save()
    except Person.DoesNotExist:
        new_values = {'first_name': 'John', 'last_name': 'Lennon'}
        new_values.update(defaults)
        obj = Person(**new_values)
        obj.save()

    以上的方法使用update_or_create实现

    obj, created = Person.objects.update_or_create(
        first_name='John', last_name='Lennon',
        defaults={'first_name': 'Bob'},
    )
  • 相关阅读:
    nuxt使用pdfjs-dist插件实现pdf预览
    package.json详细介绍
    encodeURI()和encodeURIComponent() 区别
    前端预览pdf——文件流
    fatal: unable to access 'https://github.com/xxxxx/xxxx.git/': Failed to connect to github.com port 443: Timed out
    vue分隔输入验证码
    Vue简单实现滚动到底部加载数据
    nuxt pdf在线预览
    Eclipse入门-HelloWorld
    多任务学习算法综述
  • 原文地址:https://www.cnblogs.com/harryblog/p/12034640.html
Copyright © 2011-2022 走看看