zoukankan      html  css  js  c++  java
  • get_or_create update_or_create

    django/query.py at master · django/django https://github.com/django/django/blob/master/django/db/models/query.py


    def get_or_create(self, defaults=None, **kwargs):
    """
    Look up an object with the given kwargs, creating one if necessary.
    Return a tuple of (object, created), where created is a boolean
    specifying whether an object was created.
    """
    # The get() needs to be targeted at the write database in order
    # to avoid potential transaction consistency problems.
    self._for_write = True
    try:
    return self.get(**kwargs), False
    except self.model.DoesNotExist:
    params = self._extract_model_params(defaults, **kwargs)
    return self._create_object_from_params(kwargs, params)


    def update_or_create(self, defaults=None, **kwargs):
    """
    Look up an object with the given kwargs, updating one with defaults
    if it exists, otherwise create a new one.
    Return a tuple (object, created), where created is a boolean
    specifying whether an object was created.
    """
    defaults = defaults or {}
    self._for_write = True
    with transaction.atomic(using=self.db):
    try:
    obj = self.select_for_update().get(**kwargs)
    except self.model.DoesNotExist:
    params = self._extract_model_params(defaults, **kwargs)
    # Lock the row so that a concurrent update is blocked until
    # after update_or_create() has performed its save.
    obj, created = self._create_object_from_params(kwargs, params, lock=True)
    if created:
    return obj, created
    for k, v in resolve_callables(defaults):
    setattr(obj, k, v)
    obj.save(using=self.db)
    return obj, False



  • 相关阅读:
    【科普杂谈】计算机按下电源后发生了什么
    【VS开发】使用WinPcap编程(1)——获取网络设备信息
    【VS开发】使用WinPcap编程(1)——获取网络设备信息
    微信公众平台消息接口PHP版
    编码gbk ajax的提交
    mysql 查询
    js cookie
    js同域名下不同文件下使用coookie
    去掉A标签的虚线框
    jquery切换class
  • 原文地址:https://www.cnblogs.com/rsapaper/p/13334115.html
Copyright © 2011-2022 走看看