Is there a way to increment the year on filtered objects using the update() method?
I am using:
python 2.6.5
django 1.2.1 final
mysql Ver 14.14 Distrib 5.1.41
I know it's possible to do something like this:
today = datetime.datetime.today()
for event in Event.objects.filter(end_date__lt=today).iterator():
event.start_date = festival.start_date + datetime.timedelta(365)
event.end_date = festival.end_date + datetime.timedelta(365)
event.save()
However, in some cases, I would prefer to use the update() method.
# This does not work..
Event.objects.all().update(
start_date=F('start_date') + datetime.timedelta(365),
end_date=F('end_date') + datetime.timedelta(365)
)
With the example above, I get:
Warning: Truncated incorrect DOUBLE value: '365 0:0:0'
The sql query it's trying to make is:
UPDATE `events_event` SET `start_date` = `events_event`.`start_date` + 365 days, 0:00:00, `end_date` = `events_event`.`end_date` + 365 days, 0:00:00
I found something in the mysql guide, but this is raw sql!
SELECT DATE_ADD('2008-12-15', INTERVAL 1 YEAR);
Any idea?
Relativedelta takes many time arguments, from seconds to years...
Have you seen this: Increasing a datetime field with queryset.update ? I also remember successfully using queryset .update() with timedelta with MySQL backend.
One potential cause of "Warning: Data truncated for column X" exception is the use of non-whole day values for the timedelta being added to the DateField - it is fine in python, but fails when written to the mysql db. If you have a DateTimeField, it works too, since the precision of the persisted field matches the precision of the timedelta.
I.e.:
Quick but ugly: