Home >Database >Mysql Tutorial >How to Achieve MySQL\'s GROUP_CONCAT Functionality in Django?
In Django, GROUP_CONCAT is not built-in, but it can be emulated using a custom Aggregate Function.
To create a custom Aggregate Function for GROUP_CONCAT, follow these steps:
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)
This class defines the GROUP_CONCAT function and its behavior.
To use your custom Aggregate Function, simply include it in your query as follows:
query_set = Fruits.objects.values('type').annotate(count=Count('type'), name=Concat('name')).order_by('-count')
This will return a QuerySet with the desired results:
apple, 2, "fuji,mac" orange, 1, "navel"
The above is the detailed content of How to Achieve MySQL\'s GROUP_CONCAT Functionality in Django?. For more information, please follow other related articles on the PHP Chinese website!