我试图显示有关子对象以及包含和不包含孙对象的子对象的摘要信息。这三个工作中有两个工作,但效果不是很好。我找不到所有包含孙对象的子对象的结果集,尽管不包含孙对象的对象的结果也可以。
我的模型是Campaign,Lead和LeadQA。
模型(相关)
class Campaign(models.Model):
id = models.IntegerField(primary_key=True, unique=True)
class Lead(models.Model):
campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)
class LeadQA(models.Model):
lead = models.ForeignKey(Lead, on_delete=models.CASCADE)
观看次数(相关)
lead_count_with_qa = list(Lead.objects.filter(campaign__id=pk, leadqa__lead=True).values_list('cid').annotate(Count('id')))
lead_count_without_qa = list(Lead.objects.filter(campaign__id=pk, leadqa=None).values_list('cid').annotate(Count('id')))
lead_qa_count = list(LeadQA.objects.filter(lead__campaign__id=pk).values_list('qa_status').annotate(Count('id')))
我只得到一个Lead_count_with_qa的空白列表。我尝试了多种排列,并且肯定有一些相关的leadQA对象以该对象为外键。
答案 0 :(得分:0)
对于质量检查线索:
Lead.objects.filter(campaign__id=pk).annotate(qa_count=Count('leadqa')).filter(qa_count__gt=0)
对于没有质量检查的销售线索:
Lead.objects.filter(campaign__id=pk).annotate(qa_count=Count('leadqa')).filter(qa_count=0)
答案 1 :(得分:0)
简化为.counts()并使用.exclude()查找具有质量检查事件的销售线索是最适合我的用例的
lead_count_with_qa = Lead.objects.filter(campaign__id=pk).exclude(leadqa=None).count()
lead_count_without_qa = Lead.objects.filter(campaign__id=pk, leadqa=None).count()
感谢HåkenLid