在 Django 中取得 GROUP_CONCAT 功能
擴充 MySQL 中 GROUP_CONCAT 的概念,Django 提供了另一個方法來實現類似的結果。在 Django 中,可以透過使用自訂聚合函數來模擬 GROUP_CONCAT。
建立 Concat 聚合函數:
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)
使用此自訂聚合函數,您可以現在可以在 Django 中執行 GROUP_CONCAT 操作查詢集。
用法範例:
考慮包含下列資料的 Fruits表:
id | type | name |
---|---|---|
0 | apple | fuji |
1 | apple | mac |
2 | orange | navel |
檢索不同水果類型的計數以及以逗號分隔的姓名列表:
query_set = Fruits.objects.values('type').annotate(count=Count('type'), name = Concat('name')).order_by('-count')
這個查詢集將返回以下結果:
type | count | name |
---|---|---|
apple | 2 | fuji,mac |
orange | 1 | navel |
以上是如何在 Django 複製 MySQL 的 GROUP_CONCAT 功能?的詳細內容。更多資訊請關注PHP中文網其他相關文章!