Skip to content

Instantly share code, notes, and snippets.

@samirbr
Created July 30, 2015 17:16
Show Gist options
  • Save samirbr/da4bdca60c29e002d988 to your computer and use it in GitHub Desktop.
Save samirbr/da4bdca60c29e002d988 to your computer and use it in GitHub Desktop.
COALESCE
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,)
import CF from cf
questions = Question.objects.filter(parent_id=form_id).annotate(none=CF('option_none', False), dkda=CF('option_dkda', False)).values('id',
'name', 'none', 'dkda')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment