Increasing a datetime field with queryset.update

2019-08-14 18:04发布

My model looks like this

class MyModel(models.Model):
    end_time = DateTimeField()

and this is what I'm trying to achieve:

m=MyModel.objects.get(pk=1)
m.end_time += timedelta(seconds=34)
m.save()

but I want to do it with update() to avoid race conditions:

MyModel.objects.filter(pk=1).update(end_time=F('end_time')+timedelta(seconds=34))

but it doesn't work. Is this possible with the django ORM or is raw SQL the only option?

1条回答
Explosion°爆炸
2楼-- · 2019-08-14 18:24

This is completely possible. Not sure if you're looking at a cached value for your end_time, but here is a test I just ran:

>>> e = Estimate.objects.get(pk=17)
>>> e.departure_date
datetime.datetime(2010, 8, 12, 0, 1, 8)
>>> Estimate.objects.filter(pk=17).update(departure_date=F('departure_date')+timedelta(seconds=34))
1
>>> e.departure_date
datetime.datetime(2010, 8, 12, 0, 1, 8)
>>> e = Estimate.objects.get(pk=17)
>>> e.departure_date
datetime.datetime(2010, 8, 12, 0, 1, 42)
查看更多
登录 后发表回答