Ticket #26327: expressions.py

File expressions.py, 1.5 KB (added by Tomasz Nowak, 6 years ago)
Line 
1from django.db.models import Expression
2
3__all__ = [
4    'JsonBuildObject',
5]
6
7
8class JsonBuildObject(Expression):
9    template = 'JSON_BUILD_OBJECT(%(expressions)s)'
10
11    def __init__(self, expressions, output_field, **extra):
12      super(JsonBuildObject, self).__init__(output_field=output_field)
13      for expression in expressions:
14          if not hasattr(expression, 'resolve_expression'):
15              raise TypeError('%r is not an Expression' % expression)
16      self.expressions = expressions
17      self.extra = extra
18
19    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
20        c = self.copy()
21        c.is_summary = summarize
22        for pos, expression in enumerate(self.expressions):
23            c.expressions[pos] = expression.resolve_expression(query, allow_joins, reuse, summarize)
24        return c
25
26    def as_sql(self, compiler, connection):
27        sql_expressions, sql_params = [], []
28        for expression in self.expressions:
29            sql, params = compiler.compile(expression)
30            # "By convention, the argument list consists of alternating keys and values"
31            sql_expressions.append("'%s'" % expression.target.column)
32            sql_expressions.append(sql)
33            sql_params.extend(params)
34        self.extra['expressions'] = ','.join(sql_expressions)
35        return self.template % self.extra, sql_params
36
37    def get_source_expressions(self):
38        return self.expressions
39
40    def set_source_expressions(self, expressions):
41        self.expressions = expressions
42
Back to Top