使用django进行条件更新或创建
测试模型使用django进行条件更新或创建,django,postgresql,sql-update,Django,Postgresql,Sql Update,测试模型 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
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)
我想更新模型,如果它存在,并且它在时间上的修改_小于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';
插入房间值(1,'2018-04-30 18:15:32.96468+04:30','2018-04-30 18:15:32.96468+04:30','room-A',30)中的冲突(id)DO UPDATE SET capacity=10,其中room.modified_位于<'2017-04-30 18:15:32.96468+04:30';
此外,我还想知道我编写的SQL查询是原子查询还是非原子查询 第一选项
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
)
- 我们检查
是否小于modified\u at
your\u日期
- 那么这个条件的值是10
- 否则,我们使用
F('capacity')
Room.objects.update_or_create(name='new_name',
defaults={'name':'new_name','capacity':conditition})
此代码易受竞争条件的影响。我们可以将此代码放入原子事务块中,但我只是想知道是否有更好的方法我编辑了我的答案,添加了另一种方法,这一种更有效@user9724623这真是太棒了@Lemayzeur,但是我必须为模型中的每个属性添加条件,而不是批量更新,即,如果条件满足或保持不变,则更新每个属性。请看我上面的查询,以便更清楚地了解我的意思,因此您不需要使用
update\u或\u create
,而是queryset.update()
它将执行您想要的操作,但如果行不存在,它将不会创建,并且我希望-如果行存在,则仅当时间条件满足其他条件时才更新创建新行
Room.objects.update_or_create(name='new_name',
defaults={'name':'new_name','capacity':conditition})