Django查询获取重复多少封电子邮件的次数

时间:2015-08-26 08:24:07

标签: python django django-models django-orm

我正在使用客户模式

    class Customer(models.Model):
        id = models.AutoField(primary_key=True)
        email = models.EmailField()

For eg: table has following data:
    id Email 
    101  a@abc.com
    102  b@abc.com
    103  c@abc.com
    104  a@abc.com
    105  b@abs.com
    106  b@abc.com
    107  d@abc.com
    108  d@abc.com

I want following Output:

    number of times  number of emails
    1     1  (c@abc.com)
    2     2  (d@abc.com, a@abc.com)
    3     1  (b@abc.com)

我想要一个查询来获取电子邮件重复的次数:

我尝试了以下查询 Customer.objects.all()。值( '电子邮件')。注释(总=计数( '电子邮件'))。ORDER_BY( '总') 这给出了以下输出

   [  
       {  
          'total':1,
          'email':u'cgaujjlitU@example.com'
       },
       {  
          'total':1,
          'email':u'fgh@dfg.com'
       },
       {  
          'total':1,
          'email':u'jay@dfg.com'
       },
       {  
          'total':1,
          'email':u'test3@gmail.com'
       },

       {  
          'total':1,
          'email':u'tester19@fgh.com'
       },
       {  
          'total':2,
          'email':u'carlos+bj1@fgh.io'
       },

       {  
          'total':17,
          'email':u'dfe@sedd.com'
       }
    ]

2 个答案:

答案 0 :(得分:3)

aggregated_list = Customer.objects.all().values('email').annotate(total=Count('email')).order_by('total') 

email_occurance = {}
for item in aggregated_list:
    get_total = item['total']
    if get_total not in email_occurance:
       email_occurance[get_total] = (item['email'],)
    else:
       existing_email_tuple = email_occurance[get_total]
       existing_email_list = list(existing_email_tuple)
       existing_email_list.append(item['email'])
       new_email_tuple = tuple(existing_email_list)
       email_occurance[get_total] = new_email_tuple

会给你:

email_occurance= {
    1: ('cgaujjlitU@example.com', 
        'fgh@dfg.com', 
        'jay@dfg.com', 
        'test3@gmail.com', 
        'tester19@fgh.com'
        ), 
    2: ('carlos+bj1@fgh.io',), 
    17: ('dfe@sedd.com',)
    }

这是您需要的输出吗?

答案 1 :(得分:2)

您需要进入原始SQL的世界,但并非所有数据库都支持它。使用postgresql,你需要在mysql和sqlite中查看array_agg,使用的函数是group_concat