问题
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