这就是我正在尝试做的事情。
例如,我有一个包含年份的列表years = [2002, 2003, 2004]
我有一个SomethingModel
with a DateField
我想做一个查询,该查询将返回属于该年的所有对象:
我知道这个作品:
SomethingModel.objects.filter(date__year=2003)
SomethingModel.objects.filter(date__in=[list with dates])
所以我尝试过这个:
SomethingModel.objects.filter(date__year__in=years)
但这给我返回了这个错误:
FieldError: Join on field 'date' not permitted. Did you misspell 'year' for the lookup type?
有谁知道如何做到这一点?以直接的方式..
谢谢!
你不能,如果你看查询集文档 https://docs.djangoproject.com/en/dev/ref/models/querysets
Entry.objects.filter(pub_date__year=2005)
变为 SQL 等效项:
SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31 23:59:59.999999';
所以你不能在概念上混合 __in 和 __date 。无论如何,您不能混合后缀,因为第一个“后缀”将被解释为不存在的关系。
您需要使用小于过滤器和大于过滤器,或者,如果列表不连续,则需要使用额外的 where 字段,例如:
SomethingModel.objects.extra(where=["YEAR(date) IN (" + ",".join([str(x) for x in [2003, 2008, 2010]]) + ")"])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)