Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Fixed #27849 Add a variant of ArrayAgg that supports filtering #8073

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 45 additions & 1 deletion django/contrib/postgres/aggregates/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,51 @@ def convert_value(self, value, expression, connection, context):
if not value:
return []
return value



class ArrayAggFilter(ArrayAgg):
template = '%(function)s(%(expressions)s) FILTER (WHERE %(conditions)s)'

def __init__(self, *args, where=None, **kwargs):
super().__init__(*args, **kwargs)
self.where = where

def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
expr = super().resolve_expression(query, allow_joins, reuse, summarize, for_save)
expr.where = expr.where.resolve_expression(query, allow_joins, reuse, summarize, False)
return expr

# http://cathyreisenwitz.com/wp-content/uploads/2016/01/no.jpg
# So I kind of have to copy + paste the as_sql implementation here, as you can't access `params` or `data`
# easily. This works, lets leave it be for now.

def as_sql(self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context):
connection.ops.check_expression_support(self)
sql_parts = []
params = []
for arg in self.source_expressions:
arg_sql, arg_params = compiler.compile(arg)
sql_parts.append(arg_sql)
params.extend(arg_params)
data = self.extra.copy()
data.update(**extra_context)
# Use the first supplied value in this order: the parameter to this
# method, a value supplied in __init__()'s **extra (the value in
# `data`), or the value defined on the class.
if function is not None:
data['function'] = function
else:
data.setdefault('function', self.function)
template = template or data.get('template', self.template)
arg_joiner = arg_joiner or data.get('arg_joiner', self.arg_joiner)
data['expressions'] = data['field'] = arg_joiner.join(sql_parts)

filter_sql, filter_params = compiler.compile(self.where)

data['conditions'] = filter_sql
params.extend(filter_params)
return template % data, params


class BitAnd(Aggregate):
function = 'BIT_AND'
Expand Down