原始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'))
# 待验证
方法二:
当模型查询API不够用时,您可以回退到编写原始SQL。Django为您提供了两种执行原始SQL查询的方法:您可以使用Manager.raw()执行原始查询并返回模型实例,也可以完全避免模型层并直接执行自定义SQL。
Django gives you two ways of performing raw SQL queries: you can use Manager.raw()
to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly.
使用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实现进行实际聚合。