Home > Mobile >  How to filter using a function in the left side of an expression?
How to filter using a function in the left side of an expression?

Time:04-29

It is possible to execute a filter with the Django ORM using the Replace function on the left side? It would be to achieve something like this query:

select * from my_table where replace(field, '-', '') = 'value'

If I try to use the function at the right side, inside the filter function, I'm receiving this error: keyword can't be an expression

CodePudding user response:

Use the Replace database function to create an annotated field equal to your replacement that you can filter on

from django.db.models import Value
from django.db.models.functions import Replace

MyModel.objects.annotate(
    field_replaced=Replace('field', Value('-'), Value(''))
).filter(
    field_replaced='value'
)
  • Related