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



  • 相关阅读:
    CSS3选择器之:nth-child(n)
    【转】JS中,中国标准时间转化为yyyy-MM-dd
    【转】浅谈JavaScript中forEach与each
    Can't connect to MySQL server (10060)
    Linux/CentOS下安装MySql RPM Bundle
    查看CentOS/Linux的版本信息
    Java中IO流,输入输出流概述与总结
    阿里历年经典Java面试题汇总
    架构师眼中的高并发架构
    Java面试经
  • 原文地址:https://www.cnblogs.com/rsapaper/p/13334115.html
Copyright © 2011-2022 走看看