Search code examples
djangodjango-modelsdjango-orm

Django how to make dynamically OR queries with ORM


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='[email protected]'

if email and whatspp

SELECT * FROM app_table WHERE email='[email protected]' OR whatsapp='15557776655'

So the question is, is it possible to make such 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 .