Modulus Query in Django using F()

十年热恋 提交于 2019-12-10 12:57:24

问题


I want to filter for Django objects such that their "id modulo K == N" .

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

So, I can use extra() with a query like this (please correct me if I'm wrong):

Foo.objects.extra(where['id %% %s = %s' % (K,N)])

But is there a way to use 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)

I would need something like:

Foo.objects.filter(id__mod(K)=N)


回答1:


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)

The feature was implemented in #14030. For earlier versions of Django, you can use extra().




回答2:


If you think about what filter is trying to do, it's taking an attribute and performing a comparison. You aren't actually comparing id to anything, but rather are filtering based off a calculated value. extra is the most appropriate way to perform this calculation-based filtering despite it sounding like filter would be able to do that.



来源:https://stackoverflow.com/questions/19942111/modulus-query-in-django-using-f

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