django 访问原始多对多创建的表字段 [英] django accessing raw many to many created table fields

查看:27
本文介绍了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.

Django creates appname_student_subjects when I use model above.

appname_student_subjects 表看起来像这样:

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

如何访问subjects_id 字段并计算上表中subjects_id 存在的次数(然后对其进行处理).例如:如果 id 为 10 的主题存在两次,模板显示 2.我知道我应该对结果使用len",但我不知道如何访问 subject_id 字段.使用外键,我在 for 循环中这样做:

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)

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

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.

推荐答案

可以直接访问直通表.

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

这篇关于django 访问原始多对多创建的表字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆