Login

replace

Author:
atombrella
Posted:
January 25, 2017
Language:
Python
Version:
Not specified
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

  1. Django Settings Assignment Expressions aka Walrus Operator example by webology 3 weeks, 3 days ago
  2. codigo alto nivel by MrRocklion 2 months, 3 weeks ago
  3. Load template from specific app by Krzysiek555 3 months, 1 week ago
  4. PostgreSQL JSON subqueries by dolamroth 3 months, 1 week ago
  5. "Magic Link" Management Command by webology 8 months, 2 weeks ago

Comments

Please login first before commenting.