How to write Django ORM query for …. WHERE substring(field1, 1, 2) in ('AB', 'BC')?

Issue

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.

Solution

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'))

Answered By – Fabio Caccamo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published