2013-01-13 92 views
8

型號:Django的訪問原始多對多創建表中的字段

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創建appname_student_subjects。

appname_student_subjects表看起來例如,像這樣:

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

如何訪問subjects_id場和計數subjects_id在表中有多少次存在上述(然後用它做什麼)。例如:如果使用ID爲10的主題存在兩次模板顯示2.我知道我應該使用「len」結果,但我不知道如何訪問subject_id字段。 外鍵我做它像這樣在for循環中:

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

和我通過結果的模板,並在for循環內顯示出來,但是這樣它不工作這不是一個外鍵。

回答

14

您可以直接訪問直通表。

num = (Students.subjects # M2M Manager 
       .through # subjects_students through table 
       .objects # through table manager 
       .filter(student_id=10) # your query against through table 
       .count()) 
+0

下面是關於一個小細節,可能一段時間有一天節省一些其他讀者注意:'Students.subjects.through'工作,但'Subjects.student_set.through'不起作用。從設計的角度來看,這是完全可以理解的,但在現實生活中,人們首先會忘記哪一個是相關集合,並且不知道錯誤信息在說什麼。 – AlanSE