Django queryset中的模数? [英] Modulo in django queryset?
问题描述
是否已经有一种方法可以根据Django queryset中的 id%4 == 0
选择对象?
Is there already a way to select objects according to id % 4 == 0
in django queryset ?
到目前为止,我发现的唯一解决方案是编写自定义Transform,因为Postgresql中似乎支持模数,但出现错误.
The only solution I found so far is to write a custom Transform since modulo seems to be supported in Postgresql but I got errors.
这是我的代码:
from django.db.models import Lookup, Transform
from django.db.models.fields import Field, IntegerField, AutoField
class Modulo4(Transform):
lookup_name = 'modulo4'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "%s %% 4" % lhs, params
AutoField.register_lookup(Modulo4)
foos = Foo.filter(id__modulo4=0)
当评估查询集时(使用 foos.count()
或其他方法)时出现错误:
And I get an error when the queryset is evaluated (with foos.count()
or whatever):
IndexError: tuple index out of range
refering to a django file. It seems to be due to the modulo since I manage to make the custom transform work with the doc example.
关于如何实现此目标的任何想法?
Any idea on how to achieve this ?
推荐答案
我手头没有Django 1.8进行测试,但是看起来您可以使用
I don't have Django 1.8 at hand to test it, but looks like you can do this using F with annotation, like this:
Foo.objects.annotate(idmod4=F('id') % 4).filter(idmod4=0)
(Django 1.7和更早版本不支持在 annotate
中使用F)
(Django 1.7 and earlier doesn't support using F in annotate
)
对于Django 1.7和更早版本,您始终可以使用 .extra()
,但不是很漂亮:
For Django 1.7 and earlier you can always use .extra()
but it isn't very pretty:
Foo.objects.extra(where=["id %% %s = 0"], params=[4])
这篇关于Django queryset中的模数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!