Asif
Asif

Reputation: 489

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). ?

Upvotes: 3

Views: 11990

Answers (2)

Marat
Marat

Reputation: 15738

questionnaire.objects.filter(test_population__user=user).count()

Upvotes: 4

dm03514
dm03514

Reputation: 55952

test_population = TestPopulation.objects.get(user=user)
test_population.questionnaire.all()

Upvotes: 11

Related Questions