使用F()在Django中进行模量查询 [英] Modulus Query in Django using F()
问题描述
我想过滤Django对象,使其"id modulo K == N".
I want to filter for Django objects such that their "id modulo K == N" .
这是在python中完成此操作的一种方法,但我希望在filter()中使用它:
Here's a way to do it in python, but I want it in the filter():
for foo in Foo.objects.all():
if foo.id % K == N:
print foo
因此,我可以对此类查询使用extra()(如果我输入错了,请更正我):
So, I can use extra() with a query like this (please correct me if I'm wrong):
Foo.objects.extra(其中['id %%%s =%s'%(K,N)])
Foo.objects.extra(where['id %% %s = %s' % (K,N)])
但是有一种方法可以使用F()?
But is there a way to use F()?
Django支持对F()对象使用加,减,乘,除和取模运算
Django supports the use of addition, subtraction, multiplication, division and modulo arithmetic with F() objects
注意:这是非常错误的:
Note: this is very wrong:
Foo.objects.filter(id = F('id')%K)
Foo.objects.filter(id=F('id') % K)
我需要类似的东西:
Foo.objects.filter(id__mod(K)= N)
Foo.objects.filter(id__mod(K)=N)
推荐答案
Django 1.8允许您在批注中使用F()对象.语法为:
Django 1.8 allows you to use F() objects in annotations. The syntax is:
Foo.objects.annotate(id_mod=F('id') % K).filter(id_mod=n)
该功能已在#14030 中实现.对于早期版本的Django,您可以使用 extra()
.
The feature was implemented in #14030. For earlier versions of Django, you can use extra()
.
这篇关于使用F()在Django中进行模量查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!