Question:
How to make SQL queries with ORM in Django?

Problem

Here is my SQL Query


all_or_conditions = []

if request.GET.get('filter_phone'):

      all_or_conditions.append("phone='"+request.GET.get('filter_phone')+"'")

if request.GET.get('filter_email'):

      all_or_conditions.append("email='"+request.GET.get('filter_email')+"'")

if request.GET.get('filter_whatsapp'):

      all_or_conditions.append("whatsapp='"+request.GET.get('filter_whatsapp')+"'")


sql_query = "SELECT * FROM app_table WHERE " + " OR ".join(all_or_conditions)


So if only one email is set SQL-query will be like


SELECT * FROM app_table WHERE email='user@email.com'


If email and WhatsApp


SELECT * FROM app_table WHERE email='user@email.com' OR whatsapp='15557776655'


So the question is, is it possible to make such a query with Django ORM not by performing RAW queries


Solution

You can build a Q object dynamically:


phone = request.GET.get('filter_phone')

email = request.GET.get('filter_email')

whatsapp = request.GET.get('filter_whatsapp')


q = Q(pk__in=[])  

# something result-less, not to have an empty query in your disjunction 

# that would hold for all entries


if phone:

    q |= Q(phone=phone)

if email:

    q |= Q(email=email)

if whatsapp:

    q |= Q(whatsapp=whatsapp)


qs = qs.filter(q)


See >Always False Q object.


Answered by: >McPherson

Credit: >StackOverflow


Blog Links

>How to manage the Text in the container in Django?

>Fix webapp stops working issue in Django- Python webapp

>Creating a form in Django to upload a picture from the website

>Sending Audio file from Django to Vue

>How to keep all query parameters intact when changing page in Django?

>Solved: TaskList View in Django

>Implement nested serializers in the Django rest framework

>How to filter events by month in Django?

>Sorting the restframework in Django

>Ways to access instances of models in view in order to save both forms at once in Django

>What makes index.html have such kind of name in Django?

>Fix Module Not Found during Deployment- Django

>Creating a Django with existing directories, files, etc.?

>How to Read a CSV file with PHP using cURL?


Nisha Patel

Nisha Patel

Submit
0 Answers