如何查询一对多相关对象的字段?

时间:2019-10-09 20:36:46

标签: python django

所以如果我有模型Run和ExceutedTestResults

class Run(TimeStampedModel):
   RUN_TYPE_CHOICES = (
       (MANUAL_RUN, 'Manual'),
       (AUTOMATED_RUN, 'Automated'),
    )
    run_type = models.CharField(max_length=1, choices=RUN_TYPE_CHOICES)

class ExecutedTestResult(Duration):
    """Lists the results of every test case executed."""
    run = models.ForeignKey(Run, on_delete=models.CASCADE,
                            related_name='run_results')
    RESULT_TYPE_CHOICES = (
       ('P', 'Passed'),
       ('F', 'Failed'),
       ('N', 'No Run'),
       ('B', 'Blocked'),
    )
    result = models.CharField(max_length=1, choices=RESULT_TYPE_CHOICES)

我想在class RunQuerySet(QuerySet):中创建一个queryset方法,该方法将返回一个运行的查询集,这些运行在一次运行中全部通过/未运行

我不确定如何在一对多关系中做到这一点。有建议吗?

2 个答案:

答案 0 :(得分:0)

您可以在filter中查询相关模型,以获得所需的结果-运行,运行结果为通过/不运行,像这样。

Run.objects.filter(run_results__result__in=['P', 'N'])

class RunQuerySet(QuerySet):

    def passed_or_no_run(self): 
        return self.filter(run_results__result__in=['P', 'N'])

答案 1 :(得分:0)

您需要使用as_manager方法将自定义QuerySet链接到模型:

class RunQuerySet(QuerySet):

    def passed_or_no_run(self): 
        return self.filter(run_results__result__in=['P', 'N'])

class Run(TimeStampedModel):
   RUN_TYPE_CHOICES = (
       (MANUAL_RUN, 'Manual'),
       (AUTOMATED_RUN, 'Automated'),
    )
    run_type = models.CharField(max_length=1, choices=RUN_TYPE_CHOICES)

    objects = RunQuerySet.as_manager()

鉴于QuerySet模型的Run实例,您可以像这样执行passed_or_no_run

runs = Run.objects.all()
runs.passed_or_no_run()

现在,您只获得run_type值为PN

的实例,而不是 all 个运行实例。