Q C*_*ron 4 django group-by sum having django-queryset
我已经使用Django几年了但是我今天在HAVING为a 添加约束而苦苦挣扎GROUP BY.
我的查询集如下:
crm_models.Contact.objects\
.filter(dealercontact__dealer__pk__in=(265,),
dealercontact__activity='gardening',
date_data_collected__gte=datetime.date(2012,10,1),
date_data_collected__lt=datetime.date(2013,10,1))\
.annotate(nb_rels=Count('dealercontact'))
Run Code Online (Sandbox Code Playgroud)
这给了我以下MySQL查询:
SELECT *
FROM `contact`
LEFT OUTER JOIN `dealer_contact` ON (`contact`.`id_contact` = `dealer_contact`.`id_contact`)
WHERE (`dealer_contact`.`active` = True
AND `dealer_contact`.`activity` = 'gardening'
AND `contact`.`date_data_collected` >= '2012-10-01'
AND `contact`.`date_data_collected` < '2013-10-01'
AND `dealer_contact`.`id_dealer` IN (265))
GROUP BY `contact`.`id_contact`
ORDER BY NULL;
Run Code Online (Sandbox Code Playgroud)
我会得到这个HAVING约束我需要的东西:
HAVING SUM(IF(`dealer_contact`.`type`='customer', 1, 0)) = 0
Run Code Online (Sandbox Code Playgroud)
如何使用Django Queryset修复此问题?我在这个实例中需要一个查询集.
这里我只使用注释才能GROUP BY开启contact.id_contact.
编辑:我的目标是获得在dealercontact中没有"客户"关系但具有"ref"关系的联系人(当然根据WHERE子句).
class Contact(models.Model):
id_contact = models.AutoField(primary_key=True)
title = models.CharField(max_length=255L, blank=True, choices=choices_custom_sort(TITLE_CHOICES))
last_name = models.CharField(max_length=255L, blank=True)
first_name = models.CharField(max_length=255L, blank=True)
[...]
date_data_collected = models.DateField(null=True, db_index=True)
class Dealer(models.Model):
id_dealer = models.AutoField(primary_key=True)
address1 = models.CharField(max_length=45L, blank=True)
[...]
class DealerContact(Auditable):
id_dealer_contact = models.AutoField(primary_key=True)
contact = models.ForeignKey(Contact, db_column='id_contact')
dealer = models.ForeignKey(Dealer, db_column='id_dealer')
activity = models.CharField(max_length=32, choices=choices_custom_sort(ACTIVITIES), db_index=True)
type = models.CharField(max_length=32, choices=choices_custom_sort(DEALER_CONTACT_TYPE), db_index=True)
Run Code Online (Sandbox Code Playgroud)
我通过在DealerContact:is_ref和中添加两个二进制字段来解决这个问题is_customer.
如果type='ref'那时is_ref=1和is_customer=0.否则,如果type='customer'再is_ref=0和is_customer=1.
因此,我现在可以使用annotate(nb_customers=Sum('is_customer'))然后使用filter(nb_customers=0).
最终的查询集包括:
Contact.objects.filter(dealercontact__dealer__pk__in=(265,),
dealercontact__activity='gardening',
date_data_collected__gte=datetime.date(2012,10,1),
date_data_collected__lt=datetime.date(2013,10,1))\
.annotate(nb_customers=Sum('dealercontact__is_customer'))\
.filter(nb_customers=0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7545 次 |
| 最近记录: |