django: ORM實現group by/group_concat功能


 

原始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實現進行實際聚合。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM