如何在同一个查询中使用__year和__in? [英] how to use __year and __in in the same query?

查看:120
本文介绍了如何在同一个查询中使用__year和__in?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里是我要做的。

我有一个名单,里面有几年,例如 years = [2002,2003,2004]

,我有一个 SomethingModel DateField

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:

我知道这个工作: / p>

I known this work:

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

所以我试过这个:

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..

谢谢!

推荐答案

如果您查看查询文件

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。您不能混合后缀,因为第一个后缀将被解释为不存在的关系。

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

这篇关于如何在同一个查询中使用__year和__in?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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