由于时区原因,在django中查询datetime对象不起作用

时间:2019-11-28 17:13:45

标签: python django django-timezone

由于时区问题,我面临查询结果错误的问题。我已经阅读了几个答案,但是其中大多数都建议使用USE_TZ = False。但是由于时区的某些依赖性,我们无法做到这一点。

blog = Post.objects.filter(date_posted__year=2019, date_posted__month=11)
blog[0]
  

Post:asfd随机新印度safasfd adf嘿

blog[0].date_posted
  

datetime.datetime(2019,11,26,20,33,58,tzinfo =)

blog[0].date_posted.day
  

26

当我在第26天查询时,它会引发错误:

Post.objects.get(date_posted__year=2019, date_posted__month=11, date_posted__day=26, slug=blog[0].slug)

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get
    self.model._meta.object_name
Blog.models.Post.DoesNotExist: Post matching query does not exist.

但它在第27天有效。

Post.objects.get(date_posted__year=2019, date_posted__month=11, date_posted__day=27, slug=blog[0].slug)

输出:

<Post: asfd random new india safasfd adf hey>


我尝试过:

Post.objects.get(date_posted=datetime.date(2019, 11, 27))

抛出:

/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1365: RuntimeWarning: DateTimeField Post.date_posted received a naive datetime (2019-11-27 00:00:00) while time zone support is active.
  RuntimeWarning)

使用此:

Post.objects.get(date_posted=datetime(2019, 11, 26, tzinfo=pytz.timezone('Asia/Kolkata')))

抛出:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/insol/webD/trydjango/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get
    self.model._meta.object_name
Blog.models.Post.DoesNotExist: Post matching query does not exist.

有没有办法解决这个问题?

0 个答案:

没有答案