Login

replace

Author:
atombrella
Posted:
January 25, 2017
Language:
Python
Version:
Not specified
Tags:
text replace
Score:
0 (after 0 ratings)

Small example of how to write your own function. This is not available in Django. The function just replaces static text strings, regular expressions are not supported.

The syntax is the same in SQLite, PostgreSQL, MySQL and Oracle.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.db.models import F, Func, Value


class Replace(Func):
    function = 'REPLACE'

    def __init__(self, expression, text, replacement=None):
        if not hasattr(expression, 'resolve_expression'):
            raise ValueError('Please pass a valid expression')
        if text is None:
            raise ValueError('Replacing null does not seem sane ...')
        self.text = Value(text)
        self.replacement = Value('' if replacement is None else replacement)
        self.expression = expression
        super().__init__(self.expression, self.text, self.replacement)


# it's then possible to use it to replace text in expressions:
Customer.objects.filter(name='Bert').update(name=Replace(F('name'), 'Bert', 'Ernie')

More like this

Comments

Please login first before commenting.