Skip to content

Instantly share code, notes, and snippets.

@clayadavis
Last active August 23, 2016 15:07
Show Gist options
  • Save clayadavis/01c745ee8140fc14ce86 to your computer and use it in GitHub Desktop.
Save clayadavis/01c745ee8140fc14ce86 to your computer and use it in GitHub Desktop.
Group Concat aggregate for Django 1.4
from django.db.models import Aggregate, fields
from django.db.models.sql.aggregates import Aggregate as SQLAggregate
class SQLConcat(SQLAggregate):
sql_function = 'GROUP_CONCAT'
sql_template = ('%(function)s(%(distinct)s%(field)s'
' SEPARATOR "%(separator)s")')
def __init__(self, col, separator=', ', distinct=False, **extra):
super(SQLConcat, self).__init__(col, separator=separator,
distinct=distinct and 'DISTINCT ' or '', **extra)
class Concat(Aggregate):
def add_to_query(self, query, alias, col, source, is_summary):
# This is a hack for 1.4 compatibility.
# If your version is > 1.4, try without.
source = fields.DateTimeField()
# End hack
aggregate = SQLConcat(col, source=source, is_summary=is_summary,
**self.extra)
query.aggregates[alias] = aggregate
name = 'Concat'
## Example
# (Book.objects.select_related('author')
# .values('author__name')
# .annotate(titles=Concat('title', distinct=True, separator='; '))
# )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment