使用Django的条件update_or_create [英] Conditional update_or_create with django

查看:1263
本文介绍了使用Django的条件update_or_create的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试模型

  class Room(models.Model):

这家商店可用房间的详细信息

名称= models.CharField(
null = False,
blank = False,
max_length = 100,
help_text ='输入房间名称'

容量= models.PositiveIntegerField(
null = False,
blank = False,
help_text ='输入数字人的房间可以容纳'

created_at = models.DateTimeField(auto_now_add = True)
modified_at = models.DateTimeField(auto_now = True)

我想更新模型(如果存在),并且其Modifyd_at时间小于x时间,否则只需创建模型即可。
作为参考,它是我希望django执行的原始SQL。

 插入房间值(1,'2018 -04-30 18:15:32.96468 + 04:30','2018-04-30 18:15:32.96468 + 04:30','Room-A',30)在CONFLICT(id)上执行SET SET UPDATE = 10 WHERE room.modified_at< ‘2017-04-30 18:15:32.96468 + 04:30’; 

我还想知道我编写的SQL查询是否是原子的

解决方案

以下示例可能会正常工作



第一种选择

 尝试:
obj = Room.objects.get(
id = id,#test与其他字段(如果需要
),如果obj.modified_at<日期时间:
obj.capacity = 10
obj.save()
否则:
obj = Room.objects.create(
#字段属性

,但Room.DoesNotExist除外:
obj = Room.objects.create(
#字段属性

第二个选项



,也可以使用 django的条件表达式



<从django.db.models导入pre> ,案例,当
导入datetime

your_date = datetime.datetime.now()
条件=案例(When(modified_at__lt = your_date,then = 10),default = F('capacity'))




  • 我们检查 modified_at 是否小于您的日期

  • 那么这个条件的值是10,

  • 否则,我们保持与<$相同的字段值c $ c> F('capacity')



其余代码 >

  Room.objects.update_or_create(name ='new_name',
defaults = {'name':'new_name ','capacity':conditition})


Test model

class Room(models.Model):
    """
    This stores details of rooms available
    """
    name = models.CharField(
        null=False,
        blank=False,
        max_length=100,
        help_text='Enter the name of the room'
    )
    capacity = models.PositiveIntegerField(
        null=False,
        blank=False,
        help_text='Enter the number of person\'s the room can accommodate'
    )
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

I want to update the model if it exists and its modified_at time is less than say x time otherwise just create the model. For reference here it the raw sql I want django to execute.

INSERT INTO room VALUES (1,'2018-04-30 18:15:32.96468+04:30','2018-04-30 18:15:32.96468+04:30','Room-A',30) ON CONFLICT(id) DO UPDATE SET capacity=10 WHERE room.modified_at < '2017-04-30 18:15:32.96468+04:30';

Also I would like to know if the SQL query I'have written is atomic or not

解决方案

The following examples may work properly

1st Option

try:
    obj = Room.objects.get(
        id=id, # test with other fields if you want
    )
    if obj.modified_at < DATETIME:
        obj.capacity = 10
        obj.save()
    else:
        obj = Room.objects.create(
            # fields attributes
        )
except Room.DoesNotExist:
    obj = Room.objects.create(
        # fields attributes
    )

2nd Option

or you can do so with Conditional Expression of django

from django.db.models import F, Case, When
import datetime

your_date = datetime.datetime.now()
condition = Case(When(modified_at__lt=your_date,then=10),default=F('capacity'))

  • We check whether modified_at is less than your_date
  • then the value of this condition is 10,
  • else, we keep the same value of the field with F('capacity')

rest of the code

Room.objects.update_or_create(name='new_name',
           defaults={'name':'new_name','capacity':conditition})

这篇关于使用Django的条件update_or_create的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆