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. "Magic Link" Management Command by webology 4 months, 2 weeks ago
  2. Closest ORM models to a latitude/longitude point by simonw 4 months, 2 weeks ago
  3. Log the time taken to execute each DB query by kennyx46 4 months, 2 weeks ago
  4. django database snippet by ItsRLuo 4 months, 2 weeks ago
  5. Serialize a model instance by chriswedgwood 5 months, 2 weeks ago

Comments

Please login first before commenting.