Search code examples
djangodjango-modelsdjango-templatesdjango-views

django accessing raw many to many created table fields


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.


Solution

  • You can access the through table directly.

    num = (
        Student.subjects          # M2M Manager
          .through                # subjects_student through table
          .objects                # through table manager
          .filter(student_id=10)  # your query against through table
          .count()
    )