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