无法使用年份和月份过滤查询集 [英] Unable to filter a queryset by using year and month

查看:38
本文介绍了无法使用年份和月份过滤查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模特是:

class Procedure(models.Model):
    procid = models.AutoField(primary_key=True, unique=True)
    timestr = models.DateTimeField(default=timezone.now)
    template = models.ForeignKey(ProcedureTemplate, on_delete=models.CASCADE, blank=True, null=True)
    clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
    doctor = models.ForeignKey(doctor, on_delete=models.SET_NULL, blank=True, null=True)
    customer = models.ForeignKey(customer, on_delete=models.CASCADE, null=False)

我试图按年份和月份过滤模型属性上的查询集.

I am trying to filter a queryset by year and month on a model property.

如果我按年份过滤:

procedures = Procedure.objects.filter(clinic = clinicobj, timestr__year=2020)
for proc in procedures:
    print(f'{proc.pk} {proc.timestr}')

我得到:

66 2020-01-08 12:38:37.237585+00:00
67 2020-01-11 15:40:00.344492+00:00
68 2020-01-12 04:50:56.190794+00:00
69 2020-01-26 05:58:36.962205+00:00
70 2020-01-29 09:51:59.038017+00:00
71 2020-02-01 14:24:18.921779+00:00
72 2020-02-09 06:20:30.993496+00:00
73 2020-02-15 10:23:09.068201+00:00
74 2020-02-15 14:04:29.368066+00:00
75 2020-02-16 06:25:09.702327+00:00
76 2020-02-19 14:05:19.369457+00:00
77 2020-02-20 11:13:35.934392+00:00

但是,当我尝试通过增加月份来缩小范围时,没有任何结果.怎么了?

However when I try to narrow it down by adding the month, I am getting no results. What's wrong here?

Procedure.objects.filter(clinic = clinicobj, timestr__year=2020, timestr__month=2)

<QuerySet []>

Procedure.objects.filter(clinic = clinicobj, timestr__year=2020).filter(clinic = clinicobj, timestr__month=2)

<QuerySet []>

推荐答案

取决于文档

当USE_TZ为True时,日期时间字段将在过滤之前转换为当前时区.这需要数据库中的时区定义."

"When USE_TZ is True, datetime fields are converted to the current time zone before filtering. This requires time zone definitions in the database."

因此,如果您使用mysql,则可以安装pytz并使用

So if you use mysql, you can install pytz and load the time zone tables with mysql_tzinfo_to_sql.

您还可以遵循数据库文档在django中.希望对您有所帮助.

Also you can follow databases document in django.I hope it helps you.

这篇关于无法使用年份和月份过滤查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆