10

Model:

class Subjects (models.Model):
    name = models.CharField(max_length=100)
    places = models.CharField(max_length=100)


class Student (models.Model):
    name = models.CharField(max_length=40)
    lastname = models.CharField(max_length=80)
    subjects = models.ManyToManyField(Subjects, blank=True)

Django creates appname_student_subjects when I use model above.

appname_student_subjects table looks for example, like this:

id   |    student_id   |  subjects_id
-----------------------------------------
1    |    1            |  10
2    |    4            |  11
3    |    4            |  19
4    |    5            |  10
...
~1000

How can I access subjects_id field and count how many times subjects_id exists in the table above (and then do something with it). For example: If subject with id 10 exists two times the template displays 2. I know that I should use "len" with result but i don't know how to access subject_id field. With foreign keys I'm doing it like this in a for loop:

results_all = Students.objects.filter(subject_id='10')
result = len(results_all)

and I pass result to the template and display it within a for loop but it's not a foreign key so it's not working.

Chris
  • 517
  • 1
  • 9
  • 22

1 Answers1

21

You can access the through table directly.

num = (Students.subjects  # M2M Manager
               .through  # subjects_students through table
               .objects  # through table manager
               .filter(student_id=10)  # your query against through table
               .count())
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 2
    Here's a note about a small detail, which may save some other reader some time someday: `Students.subjects.through` works, but `Subjects.student_set.through` does not work. This is entirely understandable from a design perspective, but in real life, people forget which one is the related set in the first place, and have no idea what the error message is saying. – AlanSE Mar 10 '16 at 18:53