Django Postgres Replace Function

Question:

I want to find all strings, but discard unwanted characters.

I have the following rows:

test!

t!est

!t!e!st!

aaa!

I want to find all test(but remove all unwanted characters).
From above table I want to get

test!

t!est

!t!e!st!

Table.objects.filter(name=test_or_test_with some_unwanted_symbols).

I don’t know how to apply Django F and Func here.

Asked By: Paul R

||

Answers:

I would suggest using regex over here

import re
a=['test!','t!est','!t!e!st!','aaa!']
for i in a:
    k=re.sub(r"W", "", i)
    if 'test' in k:
        print (k)
Answered By: Aki003

You can use the Django Replace function (introduced in Django 2.1) [docs].

For your example, you would want to use it in an annotation:

>>> from django.db.models import Value
>>> from django.db.models.functions import Replace
>>>
>>> Thing.objects.create(name='test!')
>>> Thing.objects.create(name='t!est')
>>> Thing.objects.create(name='!t!e!st!')
>>> Thing.objects.create(name='aaa!')
>>>
>>> things = thing.objects.annotate(
>>>     clean_name=Replace('name', Value('!'), Value(''))
>>> )
>>> things.filter(clean_name='test').values("name")
<QuerySet [{'name': 'test!'}, {'name': 't!est'}, {'name': '!t!e!st!'}]>
Answered By: Greg Kaleka