Search code examples
pythondjangopostgresqldjango-modelsdjango-orm

Django Postgres Replace Function


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.


Solution

  • 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!'}]>