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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.