how to use __year and __in in the same query?

时光怂恿深爱的人放手 提交于 2019-12-05 11:07:04

You can't, if you look at the queryset documentation

Entry.objects.filter(pub_date__year=2005)

becomes the SQL equivalent:

SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31 23:59:59.999999';

So you can't mix __in and __date conceptually. You can't mix suffixes anyway since the first "suffix" will be interpreted as a non-existent relationship.

You'll need to use a less than filter and a greater than filter or, if the list isn't contiguous, an extra where field, something like:

SomethingModel.objects.extra(where=["YEAR(date) IN (" + ",".join([str(x) for x in [2003, 2008, 2010]]) + ")"])

You can try,

SomethingModel.objects.filter(date__year=[year for year in years])

If your list of years are always consecutive you can do

SomethingModel.objects.filter(date__year__gte=years[0], date__year__lte=years[-1])

You could use: SomethingModel.objects.filter(date__range=(date_1, date_2)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!