【问题标题】:Django get_object_or_404() with DateTimeField带有 DateTimeField 的 Django get_object_or_404()
【发布时间】:2016-05-17 20:14:24
【问题描述】:

我现在正在阅读“Django by Example”一书。

我在查找带参数的记录时遇到问题。

我的代码如下所示:

settings.py

TIME_ZONE = 'Asia/Seoul'

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

在 SQLite3 中,“已发布”DateTimeField 的值是:“2016-05-17 19:57:03”,即 UTC 时间。我提前 9 小时到达亚洲/首尔。所以我实际上是在 5 月 18 日凌晨 4:57 发布的。

>>> 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。

如何强制过滤条件使用 UTC 时区?

【问题讨论】:

    标签: django sqlite timezone


    【解决方案1】:

    我自己回答我的帖子。我看了说明书上说的。

    当 USE_TZ 为 True 时,日期时间字段在过滤前转换为当前时区。

    我更改了 get_absolute_url() 方法以将 UTC 转换为亚洲/首尔时区:

    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
    

    我是这样修复的,但如果有的话,我想知道更好的方法。谢谢。

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 2014-12-31
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多