(2016 年 4 月 4 日)更新:这是适用于 Django Creating your own Aggregate Functions。
使用取自 here 的自定义 Concat 聚合 (an article about the topic)
定义这个:
class Concat(models.Aggregate):
def add_to_query(self, query, alias, col, source, is_summary):
#we send source=CharField to prevent Django from casting string to int
aggregate = SQLConcat(col, source=models.CharField(), is_summary=is_summary, **self.extra)
query.aggregates[alias] = aggregate
#for mysql
class SQLConcat(models.sql.aggregates.Aggregate):
sql_function = 'group_concat'
@property
def sql_template(self):
if self.extra.get('separator'):
return '%(function)s(%(field)s SEPARATOR "%(separator)s")'
else:
return '%(function)s(%(field)s)'
#For PostgreSQL >= 9.0
#Aways use with separator, e.g. .annotate(values=Concat('value', separator=','))
class SQLConcat(models.sql.aggregates.Aggregate):
sql_function = 'string_agg'
@property
def sql_template(self):
#the ::text cast is a hardcoded hack to work with integer columns
return "%(function)s(%(field)s::text, '%(separator)s')"
#For PostgreSQL >= 8.4 and < 9.0
#Aways use with separator, e.g. .annotate(values=Concat('value', separator=','))
class SQLConcat(models.sql.aggregates.Aggregate):
sql_function = 'array_to_string'
@property
def sql_template(self):
return "%(function)s(array_agg(%(field)s), '%(separator)s')"
#For PostgreSQL < 8.4 you should define array_agg before using it:
#CREATE AGGREGATE array_agg (anyelement)
#(
# sfunc = array_append,
# stype = anyarray,
# initcond = '{}'
#);
class MyModel(models.Model):
item = models.CharField(max_length = 255)
date = models.DateTimeField()
value = models.IntegerField()
所以现在你可以这样做了:
>>> from my_app.models import MyModel, Concat
>>> MyModel.objects.values('item').annotate(values=Concat('value'))
[{'item': u'ab', 'values': u'124,433,99'}, {'item': u'abc', 'values': u'23,80'}]
要获得values 作为整数列表,您需要手动.split 并转换为int。比如:
>>> my_list = MyModel.objects.values('item').annotate(values=Concat('value'))
>>> for i in my_list:
... i['values'] = [int(v) for v in i['values'].split(',')]
...
>>> my_list
[{'item': u'ab', 'values': [124, 433, 99]}, {'item': u'abc', 'values': [23, 80]}]