计算内部多对多字段Django

时间:2016-06-16 18:42:48

标签: django django-models

假设我有以下模型:

class Analysis(Model):
    experts = ManyToManyField(Expert,
                              related_name='analysis',
                              through='AnalysisExpert')


class AnalysisExpert(Model):
    analysis = ForeignKey(Analysis)
    expert = ForeignKey(Expert

    questions = ManyToManyField(Question, through='ExpertQuestion')

class ExpertQuestion(Model):
    expert = ForeignKey(AnalysisExpert, related_name="expert_comparisons")

    question = ForeignKey('Question')

看起来我已经嵌套了ManyToManyField。分析 - >专家 - >问题

计算某些分析的问题数量的最有效方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用values_list计算单个Analysis对象的问题数。

analysis_obj.experts.all().values_list("question").count()

以上查询测试以下型号:

class Question(models.Model):
    question = models.CharField(max_length=50)


class Expert(models.Model):
    question = models.ManyToManyField(Question,
                              related_name='questions')

class Analysis(models.Model):
    experts = models.ManyToManyField(Expert,
                     related_name='analysis')