Mysql
 sql >> Database >  >> RDS >> Mysql

GROUP_CONCAT equivalente a Django

Puoi creare la tua funzione di aggregazione (doc )

from django.db.models import Aggregate

class Concat(Aggregate):
    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)

e usalo semplicemente come:

query_set = Fruits.objects.values('type').annotate(count=Count('type'),
                       name = Concat('name')).order_by('-count')

Sto usando django 1.8 e mysql 4.0.3