Skip to content

Instantly share code, notes, and snippets.

@ludoo
Created October 28, 2014 13:18
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ludoo/ca6ed07e5c8017272701 to your computer and use it in GitHub Desktop.
Save ludoo/ca6ed07e5c8017272701 to your computer and use it in GitHub Desktop.
Django aggregates GROUP_CONCAT support for MySQL
"""
From http://harkablog.com/inside-the-django-orm-aggregates.html
with a couple of fixes.
Usage: MyModel.objects.all().annotate(new_attribute=Concat('related__attribute', separator=':')
"""
from django.db.models import Aggregate
from django.db.models.sql.aggregates import Aggregate as SQLAggregate
class Concat(Aggregate):
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLConcat(col, source=source, is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
class SQLConcat(SQLAggregate):
sql_function = 'group_concat'
@property
def sql_template(self):
separator = self.extra.get('separator')
if separator:
return '%(function)s(%(field)s, "%(separator)s")'
else:
return '%(function)s(%(field)s)'
@pedromtorres
Copy link

i believe you should change the separator part to:

if separator:
            return '%(function)s(%(field)s SEPARATOR "%(separator)s")'
        else:
            return '%(function)s(%(field)s)'

@w495
Copy link

w495 commented Apr 18, 2017

Yes. return '%(function)s(%(field)s SEPARATOR "%(separator)s")' is necessary

@akshay-hazari
Copy link

akshay-hazari commented Dec 31, 2020

This module has been removed now django.db.models.sql.aggregates .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment