Django1.11.4 版本, python3.6.2
有这么一个日期字段,pub_date = models.DateTimeField(),但是按月查询却查不出来,模型如下:
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def str(self):
return self.question_text
过程如下:
python3 manage.py shell 进入交互模式,插入一条数据,查询 (省去部分import)
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q= Question.objects.get(pub_date__year=2018)
q.pub_date
返回:
datetime.datetime(2018, 1, 23, 5, 50, 44, 358162, tzinfo='UTC')
q= Question.objects.get(pub_date__month=1)
抛出错误:models.DoesNotExist,找不到匹配的数据。
使用filter:
q= Question.objects.all().filter(pub_date__year=2018)
q[0].pub_date
datetime.datetime(2018, 1, 23, 5, 50, 44, 358162, tzinfo='UTC')
指定pub_date__month=1 时搜不到数据
q= Question.objects.all().filter(pub_date__month=1)
q为空 :QuerySet [ ]