问题:
Say I have the following table called fruits:
id | type | name |
---|---|---|
0 | apple | fuji |
1 | apple | mac |
2 | orange | navel |
My goal is to ultimately come up with a count of the different types and a comma-delimited list of the names:
apple, 2, "fuji,mac"
orange, 1, "navel"
This can be easily done with GROUP_CONCAT in MySQL but I’m having trouble with the Django equivalent. This is what I have so far but I am missing the GROUP_CONCAT stuff:
query_set = Fruits.objects.values(‘type’).annotate(count=Count(‘type’)).order_by(’-count’)
I would like to avoid using raw SQL queries if possible.
Any help would be greatly appreciated!
NOTICE that Django (>=1.8) provides Database functions support. https://docs.djangoproject.com/en/dev/ref/models/database-functions/#concat
from django.db.models import Aggregate, CharField
class GroupConcat(Aggregate):
function = 'GROUP_CONCAT'
template = '%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)'
def __init__(self, expression, distinct=False, ordering=None, separator=',', **extra):
super(GroupConcat, self).__init__(
expression,
distinct='DISTINCT ' if distinct else '',
ordering=' ORDER BY %s' % ordering if ordering is not None else '',
separator=' SEPARATOR "%s"' % separator,
output_field=CharField(),
**extra
)
Usage:
LogModel.objects.values('level', 'info').annotate(
count=Count(1), time=GroupConcat('time', ordering='time DESC', separator=' | ')
).order_by('-time', '-count')
我的项目里的应用举例
from data_assets.utils.models import GroupConcat
from django.db.models.functions import Substr, StrIndex
from django.db.models import CharField
from .models import DataFlowField
fields = DataFlowField.objects.filter(table__database__business_type=3).filter(
Q(provide_department='') | Q(provide_department__isnull=True))
# for f in fields: # 优化 for-save有点慢
# f.provide_department = f.create_department.split(',')[0] if f.create_department else '未知部门'
# f.save(update_fields=['provide_department'])
# 改用StrIndex和Substr切分字符串,批量更新
fields.filter(create_department__contains=',').annotate(
smith_index=StrIndex(F('create_department'), Value(','))).annotate(
dept1=Substr(F('create_department'), 1, F('smith_index')-1, output_field=CharField())).update(
provide_department=F('dept1'))