Skip to content

Instantly share code, notes, and snippets.

@ErDmKo
Created January 24, 2014 12:08
Show Gist options
  • Save ErDmKo/8596170 to your computer and use it in GitHub Desktop.
Save ErDmKo/8596170 to your computer and use it in GitHub Desktop.
Group elements by date and get elements id list from group.
SELECT DATE_FORMAT(d, "%Y%m") as month_year, GROUP_CONCAT(id SEPARATOR ',') as ids FROM events_event GROUP BY month_year LIMIT 100
from django.db.models.aggregates import Aggregate
from django.db.models.sql.aggregates import Aggregate as SQLAggregate
class SQLConcat(SQLAggregate):
sql_function = "GROUP_CONCAT"
def __init__(self, col, separator=',', **extra):
self.sql_template = "%%(function)s(%%(field)s SEPARATOR '%s')" % separator
super(SQLConcat, self).__init__(col, source=models.DecimalField(), **extra)
class Concat(Aggregate):
name = "Concat"
def add_to_query(self, query, alias, col, source, is_summary):
aggregate = SQLConcat(col, is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
out = Event.objects.filter(d__lt=datetime.now()).extra(select={
'month_year': 'DATE_FORMAT(d, "%%m.%%Y")',
}).values('month_year').annotate(count=Concat('id'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment