Increasing a datetime field with queryset.update

倾然丶 夕夏残阳落幕 提交于 2019-12-11 07:06:44

问题


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:


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)


来源:https://stackoverflow.com/questions/3843250/increasing-a-datetime-field-with-queryset-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!