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

查看:102
本文介绍了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字段和计算上面表格中存在subject_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.

推荐答案

您可以访问直接通过表。

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())

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

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