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'},
    )
  • 相关阅读:
    利用GitHub+Node.js+Hexo搭建个人博客(一)
    更丰富的符号工具包 Font Awesome
    Markdwon入门2
    Codechef:Fibonacci Number/FN——求通项+二次剩余+bsgs
    二次剩余理论
    基姆拉尔森公式和蔡勒公式(计算星期几)
    幂方程(模意义下)
    etcd
    mysql group by
    UUID
  • 原文地址:https://www.cnblogs.com/harryblog/p/12034640.html
Copyright © 2011-2022 走看看