获取跨越关系的对象数

时间:2019-01-18 10:43:31

标签: python django django-models

我试图获取跨越关系的对象数。每个TestPlan包含n个案例。 plan_case_count()方法为我计数。每个TestPlanCase包含n个步骤。我想获取与计划相关的所有案例的所有步骤的总数。方法plan_case_step_count()应该通过迭代查询集并累加计数来做到这一点。但这是行不通的。我收到的错误消息是:

“ RelatedManager”对象没有属性“ testplanstep_set”

class TestPlan(models.Model):
    tp_title = models.CharField(max_length=200)
    tp_version = models.IntegerField()
    tp_date = models.DateField(default=timezone.now)

    def plan_case_count(self):
        """This one works"""
        return self.testplancase_set.count()

    def plan_case_step_count(self):
        """This one doesn't"""
        pcs_count = 0
        for case in self.testplancase_set:
            pcs_count += case.testplanstep_set.count()
        return pcs_count


class TestPlanCase(models.Model):
    tpc_plan = models.ForeignKey(TestPlan, on_delete=models.CASCADE)
    tpc_case = models.ForeignKey(TestCase, on_delete=models.CASCADE)
    tpc_seq_no = models.IntegerField(default=1)


class TestPlanStep(models.Model):
    tps_case =  models.ForeignKey(TestPlanCase, on_delete=models.CASCADE)
    tps_step = models.ForeignKey(TestSteps, on_delete=models.CASCADE)
    tps_ok =  models.CharField(max_length=4, choices=Choices.yes_no)
    tps_issue = models.CharField(max_length=200, blank=True)

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

请直接写计数查询:

def plan_case_step_count(self):
    return TestPlanStep.objects.filter(tps_case__tpc_plan=self).count()

这将直接使用COUNT(*)在SQL中编写一个JOIN查询。