0

How would I do the following SQL in the django ORM:

SELECT * FROM main_titlemaster WHERE id % 4 = 0

The model name is TitleMaster.

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

3

You can use the .extra():

TitleMaster.objects.extra(where=['id mod 4=0'])

https://docs.djangoproject.com/en/dev/ref/models/querysets/

David542
  • 104,438
  • 178
  • 489
  • 842
  • For anyone arriving here, considering using this solution: The docs do no recommend using it. > This is an old API that we aim to deprecate at some point in the future. – decibyte May 25 '23 at 14:12
0

According to the docs, the correct way of doing this today is using an F() expression:

Django supports the use of addition, subtraction, multiplication, division, modulo, and power arithmetic with F() objects

This should do the trick:

TitleMaster.objects.annotate(mod_four=F("id") % 4).filter(mod_four=0)
decibyte
  • 773
  • 11
  • 17