django: ORM實現group by/group_concat功能
阿新 • • 發佈:2020-08-10
原始SQl語句:selectip, group_concat(id)asidfromwhitelistgroupbyip;
方法一:
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'))
# 待驗證
方法二:
當模型查詢API不夠用時,您可以回退到編寫原始SQL。Django為您提供了兩種執行原始SQL查詢的方法:您可以使用Manager.raw()執行原始查詢並返回模型例項,也可以完全避免模型層並直接執行自定義SQL。
Django gives you two ways of performing raw SQL queries: you can useManager.raw()
toperform raw queries and return model instances
使用Manage.raw(sql語句)
class Person(models.Model): first_name = models.CharField(...) last_name = models.CharField(...) birth_date = models.DateField(...)
>>> Person.objects.raw('''SELECT first AS first_name,
... last AS last_name,
... bd AS birth_date,
... pk AS id,
... FROM some_other_table''')
方法三:
在即將推出的Django 1.8中你可以實現GroupConcat表示式,然後查詢看起來像:
Event.objects.values('slug').annotate(emails=GroupConcat('task__person__email'))
.values( ).annotate( )組合將GROUP BY設定為slug,當然GroupConcat實現進行實際聚合。