django: ORM实现group by/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'))

# 待验证

猜你喜欢

转载自www.cnblogs.com/rgxx/p/10303877.html