测试模型
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)
我想更新模型,如果它存在且其modified_at时间小于说x时间,否则只需创建模型。 在这里参考它是我希望django执行的原始sql。
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';
此外,我想知道我写的SQL查询是否是原子的
答案 0 :(得分:0)
以下示例可能正常运行
第一个选项
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
)
第二个选项
或者您可以使用django的Conditional Expression
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'))
modified_at
是否小于your_date
F('capacity')
其余代码
Room.objects.update_or_create(name='new_name',
defaults={'name':'new_name','capacity':conditition})