Django查询多对多关系

Asi*_*sif 0 python django django-models

我有以下两种模式

class Questionnaire(models.model)
     name = models.CharField(max_length=128, null=True, blank=True)
     type = models.CharField(max_length=128,choices=questionnaire_choices) 

class TestPopulation(models.Model)
      user = models.ForeignKey(User, blank=True, null=True)
      age = models.CharField(max_length=20, blank=True, null=True)
      education = models.CharField(max_length=50, blank=True, null=True, 
                                   choices=EDUCATION_CHOICES)
     questionnaire = models.ManyToManyField(Questionnaire, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)

现在如何获取特定用户(已登录用户)的问卷数量。?

dm0*_*514 5

test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()
Run Code Online (Sandbox Code Playgroud)

  • 他需要这样的号码:`test_population.questionnaire.count()` (4认同)