How to do OR queries in Django ORM?

sanju saini
May 28, 2021

--

In this tutorial, we will learn how to apply OR queries in Django ORM queryset

If your models class name is Enquiry, and field names are Email and State, and more.
A common requirement is performing OR filtering with two or more conditions. Say you want to find all Enquirys with
Email starting with ‘s’ and State starting with ‘Raj’.
Django provides two options.

|, are used as an OR(|) operator

  • queryset_1 | queryset_2
  • filter(Q(<condition_1>)|Q(<condition_2>)

The SQL query for the above condition will look something like

Similarly our ORM query would look like

Queryset = Enquiry.objects.filter(Email__startswith=”sanju”) | Enquiry.objects.filter(State__startswith=”raj”)

Alternatively, you can use the Q objects.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

sanju saini
sanju saini

Written by sanju saini

Senior Software Engineer with 4.5+ years of experience in full-stack development, specializing in Python, Golang, PHP, Django, FastAPI, React, and RESTful APIs.

No responses yet

Write a response