Django的ORM实现group_concat的分组查询

原始SQl语句:select ip, group_concat(id) as id from whitelist group by ip;
Django-ORM:
1、创建Concat类

from django.db.models import Aggregate, CharField

class Concat(Aggregate):
    """ORM用来分组显示其他字段 相当于group_concat"""
    function = 'GROUP_CONCAT'
    template = '%(function)s(%(distinct)s%(expressions)s)'

    def __init__(self, expression, distinct=False, **extra):
        super(Concat, self).__init__(
            expression,
            distinct='DISTINCT ' if distinct else '',
            output_field=CharField(),
            **extra)

2、模型管理器查询

WhiteList.objects.values('ip').annotate(id=Concat('id'))

你可能感兴趣的:(Django的ORM实现group_concat的分组查询)