planetp planetp - 4 months ago 28
Python Question

How to make a query using a database function with Django ORM?

I want to query the database using a

clause like this in Django ORM:

WHERE LOWER(col_name) = %s


WHERE LOWER(col_name) = LOWER(%s)

How can I do this using QuerySet API?


You can use extra to add a custom where condition using sql functions:

Author.objects.extra(where=["lower(name) = lower(%s)"], params=['Fabio'])

You want to use params instead of embedding the value directly in the query to avoid SQL injection by letting Django escape the params for you.

If you can avoid using the sql LOWER function on the param you pass (in my example 'Fabio'), then you can use annotate instead:


Note that your_name.lower() is using the python lower function, not the sql one.

I couldn't find a way to use annotate together with F() or Lower() (from django.db.models.functions import Lower) to apply Lower to your custom input, as opposed to another field.