From e5835a7cb8479ef98ea54cd91e02689d42b11702 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Mon, 17 Jul 2017 16:07:19 +0200 Subject: [PATCH] Allowed Func subclasses to add kwargs to __repr__(). Thanks Tim Graham for the review. --- django/db/models/aggregates.py | 24 ++++++------------------ django/db/models/expressions.py | 7 ++++++- 2 files changed, 12 insertions(+), 19 deletions(-) diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index 507fced8e7..bc0f3d1916 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -70,12 +70,8 @@ class Count(Aggregate): output_field=IntegerField(), **extra ) - def __repr__(self): - return "{}({}, distinct={})".format( - self.__class__.__name__, - self.arg_joiner.join(str(arg) for arg in self.source_expressions), - 'False' if self.extra['distinct'] == '' else 'True', - ) + def _get_repr_options(self): + return {'distinct': self.extra['distinct'] != ''} def convert_value(self, value, expression, connection, context): if value is None: @@ -100,12 +96,8 @@ class StdDev(Aggregate): self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP' super().__init__(expression, output_field=FloatField(), **extra) - def __repr__(self): - return "{}({}, sample={})".format( - self.__class__.__name__, - self.arg_joiner.join(str(arg) for arg in self.source_expressions), - 'False' if self.function == 'STDDEV_POP' else 'True', - ) + def _get_repr_options(self): + return {'sample': self.function == 'STDDEV_SAMP'} def convert_value(self, value, expression, connection, context): if value is None: @@ -134,12 +126,8 @@ class Variance(Aggregate): self.function = 'VAR_SAMP' if sample else 'VAR_POP' super().__init__(expression, output_field=FloatField(), **extra) - def __repr__(self): - return "{}({}, sample={})".format( - self.__class__.__name__, - self.arg_joiner.join(str(arg) for arg in self.source_expressions), - 'False' if self.function == 'VAR_POP' else 'True', - ) + def _get_repr_options(self): + return {'sample': self.function == 'VAR_SAMP'} def convert_value(self, value, expression, connection, context): if value is None: diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index dc2be87453..52aebccb8e 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -531,11 +531,16 @@ class Func(Expression): def __repr__(self): args = self.arg_joiner.join(str(arg) for arg in self.source_expressions) - extra = ', '.join(str(key) + '=' + str(val) for key, val in self.extra.items()) + extra = dict(self.extra, **self._get_repr_options()) if extra: + extra = ', '.join(str(key) + '=' + str(val) for key, val in extra.items()) return "{}({}, {})".format(self.__class__.__name__, args, extra) return "{}({})".format(self.__class__.__name__, args) + def _get_repr_options(self): + """Return a dict of extra __init__() options to include in the repr.""" + return {} + def get_source_expressions(self): return self.source_expressions