简体   繁体   中英

Django query for many to many relationship

I have following two 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)

Now how can i get number of questionnaires for the specific user (logged in user). ?

test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()
questionnaire.objects.filter(test_population__user=user).count()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM