Home > database >  How to write Django ORM query for .... WHERE substring(field1, 1, 2) in ('AB', 'BC�
How to write Django ORM query for .... WHERE substring(field1, 1, 2) in ('AB', 'BC�

Time:12-24

How to write Django ORM filter for following query.

SELECT field1, field2, field3 FROM table1 WHERE substring(field1, 1, 2) in ('AB', 'BC')

I want to write query using

Model1.objects.filter(.....)

I think sql query self explaining, I don't have to give more context.

CodePudding user response:

Is there any reason why you cannot use raw SQL queries using the raw() function?

Something like:

Model1.objects.raw('SELECT field1, field2, field3 FROM table1 WHERE substring(field1, 1, 2) in ('AB', 'BC')')

Documented here: https://docs.djangoproject.com/en/4.0/topics/db/sql/#executing-custom-sql-directly

CodePudding user response:

This can be done easily with the django ORM combining only, filter and Q expressions:

from django.db.models import Q

Model1.objects.only('field1', 'field2', 'field3').filter(Q(field1__startswith='AB') | Q(field1__startswith='BC'))
  • Related