Created
January 24, 2014 12:08
-
-
Save ErDmKo/8596170 to your computer and use it in GitHub Desktop.
Group elements by date and get elements id list from group.
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
SELECT DATE_FORMAT(d, "%Y%m") as month_year, GROUP_CONCAT(id SEPARATOR ',') as ids FROM events_event GROUP BY month_year LIMIT 100 |
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 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