有没有办法使用update()方法增加过滤对象的年份?
我正在使用:
python 2.6.5
django 1.2.1 final
mysql Ver 14.14 Distrib 5.1.41
我知道可以这样做:
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()
但是,在某些情况下,我更愿意使用update()方法。
# This does not work..
Event.objects.all().update(
start_date=F('start_date') + datetime.timedelta(365),
end_date=F('end_date') + datetime.timedelta(365)
)
通过上面的例子,我得到:
Warning: Truncated incorrect DOUBLE value: '365 0:0:0'
它试图进行的SQL查询是:
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
我在mysql指南中找到了一些东西,但这是原始的sql!
SELECT DATE_ADD('2008-12-15', INTERVAL 1 YEAR);
有什么想法吗?
答案 0 :(得分:1)
“警告:列X的数据截断”例外的一个潜在原因是使用非全日值将timedelta添加到 DateField - 它在python中很好,但写入mysql db时失败。如果您有 DateTimeField ,它也可以,因为持久字段的精度与timedelta的精度相匹配。
即:
>>> from django.db.models import F
>>> from datetime import timedelta
>>> from myapp.models import MyModel
>>> [field for field in MyModel._meta.fields if field.name == 'valid_until'][0]
<django.db.models.fields.DateField object at 0x3d72fd0>
>>> [field for field in MyModel._meta.fields if field.name == 'timestamp'][0]
<django.db.models.fields.DateTimeField object at 0x43756d0>
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3))
1L
>>> MyModel.objects.filter(pk=1).update(valid_until=F('valid_until') + timedelta(days=3.5))
Traceback (most recent call last):
...
Warning: Data truncated for column 'valid_until' at row 1
>>> MyModel.objects.filter(pk=1).update(timestamp=F('timestamp') + timedelta(days=3.5))
1L
答案 1 :(得分:0)
快而丑:
>>> a.created.timetuple()
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=2, tm_hour=2, tm_min=35, tm_se
c=14, tm_wday=3, tm_yday=307, tm_isdst=-1)
>>> time = list(a.created.timetuple())
>>> time[0] = time[0] + 1
>>> time
[2001, 11, 2, 2, 35, 14, 3, 307, -1]
>>>
答案 2 :(得分:0)
from dateutil.relativedelta import relativedelta
yourdate = datetime.datetime(2010, 11, 4, 10, 14, 54, 518749)
yourdate += relativedelta(years=+1)
Relativedelta需要很多时间参数,从几秒钟到几年......
答案 3 :(得分:0)
你见过这个:Increasing a datetime field with queryset.update?我还记得成功使用queryset .update()和timedelta与MySQL后端。