how to use __year and __in in the same query?

你离开我真会死。 提交于 2019-12-07 05:17:31

问题


So here's what I'm trying to do.
I've a list with years inside, for instance years = [2002, 2003, 2004]
and I've a SomethingModel with a DateField

I want to do a query that will return me all the objects that belongs to that year:

I known this work:

 SomethingModel.objects.filter(date__year=2003) 
 SomethingModel.objects.filter(date__in=[list with dates])

So I've tried this:

SomethingModel.objects.filter(date__year__in=years)

but this return me this error:

FieldError: Join on field 'date' not permitted. Did you misspell 'year' for the lookup type?

Does anyone has any idea how to do this? In a direct way..

Thanks!


回答1:


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]]) + ")"])



回答2:


You can try,

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



回答3:


If your list of years are always consecutive you can do

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



回答4:


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



来源:https://stackoverflow.com/questions/6440219/how-to-use-year-and-in-in-the-same-query

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