Login

Coalesce for F()

Author:
axil
Posted:
February 13, 2012
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Updating fields that allow for NULLs must take care about those NULLs.

Use case:

Message.objects.filter(id=1).update(price=CF('price', 0) + 7)

Message.objects.filter(id=1).update(status=CF('status') // 's')

Works for postgres. Supposedly works for mysql. Didn't test with other backends.

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

def __floordiv__(self, other):
    return self._combine(other, '||', False)
F.__floordiv__ = __floordiv__

class CF(F):
    """
    A coalesced expression representing the value of the given field.
    """

    def __init__(self, name, default=''):
        super(CF, self).__init__(name)
        self.default = default

    def evaluate(self, *args, **kwargs):
        res = super(CF, self).evaluate(*args, **kwargs)
        return 'COALESCE(%s, %%s)' % res[0], res[1] + (self.default,)

More like this

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

Comments

Please login first before commenting.