Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从日期字段Django中按月筛选数据_Python_Mysql_Django - Fatal编程技术网

Python 从日期字段Django中按月筛选数据

Python 从日期字段Django中按月筛选数据,python,mysql,django,Python,Mysql,Django,我需要编写一个查询,返回一个月列表中的所有对象。月份将根据日期字段计算,即(2012-10-21或2011-04-14)。当我只做一个月的时候,它就可以正常工作了 **Table.objects.filter(ad\u date\u month=month)**。假设月份=05 但是,当我试图在几个月的时间里完成这项工作时,它就不起作用了。 **Table.objects.filter(ad\u date\u month\u in=month\u list)**。假设月份列表=[11,03,01

我需要编写一个查询,返回一个月列表中的所有对象。月份将根据日期字段计算,即(2012-10-21或2011-04-14)。当我只做一个月的时候,它就可以正常工作了
**Table.objects.filter(ad\u date\u month=month)**
。假设月份=05

但是,当我试图在几个月的时间里完成这项工作时,它就不起作用了。
**Table.objects.filter(ad\u date\u month\u in=month\u list)**
。假设月份列表=[11,03,01,10]

我得到这个错误:

"Join on field 'date' not permitted. Did you misspell 'month' for the lookup type?"
Django似乎认为这是一个连接操作


请建议,我在过去两天一直遇到这个问题。

嗨,我知道这不是很好,但它会起作用

from itertools import chain

result_list = []
for mm in month_list:
    this_query = Table.objects.filter(ad_date__month=mm)
    result_list = chain(result_list, this_query)

你所要求的是可行的使用

以下理解将为您的
month\u列表中的每个月创建一个Q对象

(Q(ad_date__month=month) for month in month_list)
所有的一切都在一条线上,这是现在

Table.objects.filter(*(Q(ad_date__month=month) for month in month_list))
编辑:

您可以使用reduce函数来“或”所有这些Q对象

import operator
q_objects = (Q(ad_date__month=month) for month in month_list)
Table.objects.filter(reduce(operator.or_, q_objects))

简单地说,您只需调用Table.objects.filter(…),就不需要调用queryset first上的.all()@aamir adnan的可能副本:我尝试了您共享的链接,但对我无效。query\u set=Table.objects.all().filter(Table1\u ad\u date\u month\u in=month\u list)query_set=Table.objects.extra(其中=“+”中的“[”月(table1_ad_日期)”。join([str(x)表示月列表中的x])+”)这正是我正在做的。这里的“table1”是另一个在“table”中有外键的模型,我想你想要
Q()| Q()
而不是