Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading