Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
Chris Avatar asked Jan 13 '13 18:01

Chris


People also ask

How take data from many-to-many field in Django?

A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.

How do you use many-to-many fields?

When you add a many to many field to a model a separate table is created in the database that stores the links between two models. If you don't need to store any extra information in this third table then you don't have to define a model for it.

What is _SET all Django?

_set is associated with reverse relation on a model. Django allows you to access reverse relations on a model. By default, Django creates a manager ( RelatedManager ) on your model to handle this, named <model>_set, where <model> is your model name in lowercase.


1 Answers

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())
like image 152
Yuji 'Tomita' Tomita Avatar answered Oct 18 '22 19:10

Yuji 'Tomita' Tomita