Question

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)

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top