简体   繁体   English

Django过滤日期时间元素

[英]Django filter datetime elements

I use django 1.11.2 for my project. 我将django 1.11.2用于我的项目。 I had defined some models and all work right. 我已经定义了一些模型,并且一切正常。

Now I need to get some data from one of my models by date. 现在,我需要按日期从我的一个模型中获取一些数据。 For example all entry which have month=8, month=9.... 例如,所有具有month = 8,month = 9 ...的条目。

I have this, MyModel(....some fields...., created_date) and in models.py I have: 我有MyModel(....某些字段....,created_date),在models.py中有:

....
created_date=models.DateTimeField()
....
....
self.created_date=(datetime.now())
....

Created_date is a datetime field and its values are in this format: YYYY-MM-DD HH:MM:SS, for example 2017-08-31 14:25:58. Created_date是日期时间字段,其值采用以下格式:YYYY-MM-DD HH:MM:SS,例如2017-08-31 14:25:58。

So, I see this: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#month 所以,我看到了: https : //docs.djangoproject.com/en/1.11/ref/models/querysets/#month

And this will be perfect for me, but doesn't work. 这对我来说是完美的,但不起作用。

From shell I write this: 从外壳我写这样的:

>>> from project.models import MyModel
>>> from datetime import *
>>> MyModel.objects.all() ---> Work ok, I get all entries
>>> MyModel.objects.filter(created_date__month=8)
<QuerySet []>

In this case I get an empty Quertset. 在这种情况下,我得到一个空的Quertset。

You may probably need to set USE_TZ into False in settings.py file 您可能需要在settings.py文件中将USE_TZ设置为False

USE_TZ = False

If it is set as True ie timezone enabled, then the __month lookup will not work 如果将其设置为True即启用了timezone ,则__month查找将不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM