如何在同一查询中使用 __year 和 __in ?
这就是我正在尝试做的事情。
我有一个包含年份的列表,例如 years = [2002, 2003, 2004]
我有一个带有 DateField
的 SomethingModel
我想做一个查询,它将返回属于那一年的所有对象:
我知道这项工作:
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?
有人知道如何做到这一点吗?以直接的方式..
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能,如果你查看查询集文档
变成SQL等价:
所以你不能在概念上混合 __in 和 __date 。无论如何,您不能混合后缀,因为第一个“后缀”将被解释为不存在的关系。
您需要使用小于过滤器和大于过滤器,或者,如果列表不连续,则需要使用额外的 where 字段,例如:
You can't, if you look at the queryset documentation
becomes the SQL equivalent:
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:
你可以尝试,
You can try,
如果你的年份列表总是连续的,你可以这样做
If your list of years are always consecutive you can do
你可以使用:
SomethingModel.objects.filter(date__range=(date_1, date_2)
You could use:
SomethingModel.objects.filter(date__range=(date_1, date_2)