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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 weeks, 4 days ago
  2. Python Django CRUD Example Tutorial by tuts_station 1 month, 1 week ago
  3. Browser-native date input field by kytta 2 months, 3 weeks ago
  4. Generate and render HTML Table by LLyaudet 3 months ago
  5. My firs Snippets by GutemaG 3 months, 1 week ago

Comments

Please login first before commenting.