-
-
Save w495/59995aed5cc360c29f074bc04ad1ba52 to your computer and use it in GitHub Desktop.
Django aggregates GROUP_CONCAT support for MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
From http://harkablog.com/inside-the-django-orm-aggregates.html | |
with a couple of fixes. | |
Usage: MyModel.objects.all().annotate(new_attribute=GroupConcat('related__attribute', separator=':') | |
""" | |
from django.db.models import Aggregate | |
from django.db.models.sql.aggregates import Aggregate as SQLAggregate | |
class GroupConcat(Aggregate): | |
def add_to_query(self, query, alias, col, source, is_summary): | |
aggregate = SQLGroupConcat(col, source=source, is_summary=is_summary, **self.extra) | |
query.aggregates[alias] = aggregate | |
class SQLGroupConcat(SQLAggregate): | |
sql_function = 'GROUP_CONCAT' | |
@property | |
def sql_template(self): | |
separator = self.extra.get('separator') | |
if separator: | |
return '%(function)s(%(field)s SEPARATOR "%(separator)s")' | |
else: | |
return '%(function)s(%(field)s)' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment