django 访问原始的多对多创建的表字段

问题描述 投票:0回答:1

型号:

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

如何访问subject_id字段并计算上表中subject_id存在的次数(然后用它做一些事情)。例如:如果 id 为 10 的主题存在两次,模板将显示 2。我知道我应该在结果中使用“len”,但我不知道如何访问 subject_id 字段。 使用外键,我在 for 循环中这样做:

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

我将结果传递给模板并在 for 循环中显示它,但它不是外键,所以它不起作用。

django django-models django-templates django-views
1个回答
21
投票

您可以直接访问直通表。

num = (Students.subjects  # M2M Manager
               .through  # subjects_students through table
               .objects  # through table manager
               .filter(student_id=10)  # your query against through table
               .count())
© www.soinside.com 2019 - 2024. All rights reserved.