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'},
    )
  • 相关阅读:
    java web分页查询初试
    SQL注入原理深度解析
    JS 清除IE缓存
    Android 代码混淆及第三方jar包不被混淆
    [leetcode]Unique Paths II
    ffmpeg API录制rtsp视频流
    HDU 2045 不容易系列之(3)—— LELE的RPG难题
    Ffmpeg和SDL创建线程(转)
    “富豪相亲大会”究竟迷失了什么?
    Ffmpeg和SDL如何同步视频(转)
  • 原文地址:https://www.cnblogs.com/harryblog/p/12034640.html
Copyright © 2011-2022 走看看