带有日期时间字段的Django get_object_or_404() [英] Django get_object_or_404() with DateTimeField
问题描述
我现在正在读《 Django范例》一书.
I'm now reading the book "Django by Example".
在查找带有参数的记录时遇到问题.
I have a problem when looking up the record with parameters.
我的代码如下所示:
settings.py
settings.py
TIME_ZONE = 'Asia/Seoul'
models.py
models.py
...
published = models.DateTimeField(default=timezone.now)
...
views.py
def post_show(request, year, month, day, slug):
post = get_object_or_404(Post,
slug=slug,
status='published',
published__year=year,
published__month=month,
published__day=day)
return render(request, 'blog/default/post/show.html', {'post': post})
urls.py
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
views.post_show, name='post_show'),
MVT可以正常工作,但我认为DateTimeField,TimeZone或SQLite3出了点问题.
MVT works fine, but I believe that there's something wrong with DateTimeField, TimeZone or SQLite3.
在SQLite3中,已发布"的DateTimeField的值为:"2016-05-17 19:57:03",它是UTC时间.我要9个小时到亚洲/首尔.所以我实际上是在5月18日凌晨4:57发布的.
In SQLite3, "published" DateTimeField has the value: "2016-05-17 19:57:03" which is UTC time. I'm in Asia/Seoul ahead of 9 hours. so I actually posted at 4:57 am on May 18th.
>>> p = get_object_or_404(Post,slug='test', published__year=2016, published__month=5, published__day=18)
>>> p.title
'test'
>>> p.published
datetime.datetime(2016, 5, 17, 19, 57, 3, tzinfo=<UTC>)
DB表示它于17日发布,但我必须传递参数"18".如果我通过了17,则进入404.
DB says it's published on 17th, but I have to pass the parameter "18". If I pass 17, it thrwos 404.
如何强制过滤条件使用UTC时区?
How can I force filter condition to use UTC timezone?
推荐答案
我自己回答我的帖子.我读了说的手册.
I answer my post by myself. I read the manual which says.
当USE_TZ为True时,日期时间字段将在过滤之前转换为当前时区.
When USE_TZ is True, datetime fields are converted to the current time zone before filtering.
我更改了get_absolute_url()方法,将UTC转换为亚洲/首尔时区:
I changed get_absolute_url() method to convert the UTC to Asia/Seoul timezone:
def get_absolute_url(self):
# this line was added.
published_localtime = timezone.localtime(self.published)
return reverse('blog:post_show',
args=[
published_localtime.year,
published_localtime.strftime('%m'),
published_localtime.strftime('%d'),
self.slug
我这样修复了它,但是我想知道更好的方法.谢谢.
I fixed it like this, but I'd like to know the better way if I've got. Thank you.
这篇关于带有日期时间字段的Django get_object_or_404()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!