如何在 django 中获取多对多关系表数据?
这是我的models.py,
from django.db import models
class Course(models.Model):
Credits = (
('1', '0.75'),
('2', '1'),
('3', '2'),
('4', '3'),
('5', '4'),
('6', '5'),
('7', '6'),
)
course_code = models.CharField(max_length=20, default="CSE-101", unique=True)
course_name = models.CharField(max_length=50, default="C Language", unique=True)
course_credit = models.CharField(max_length=1, choices=Credits, default='4')
def __str__(self):
return self.course_code
class Student(models.Model):
std_name = models.CharField(max_length=40)
std_id = models.CharField(max_length=50, primary_key=True)
std_email = models.EmailField(max_length=50, unique=True, blank=True)
course = models.ManyToManyField(Course)
def __str__(self):
return self.std_id
当我在Student表中输入数据时,数据库创建一个表student_course,我想获取这个student_course数据。
我想获取每个学生注册了多少门课程以及每个课程名称的数据。我如何获取这些数据并在网页中显示这些数据?
我是 python 和 Django 的菜鸟,所以任何帮助将不胜感激。
This is my models.py
from django.db import models
class Course(models.Model):
Credits = (
('1', '0.75'),
('2', '1'),
('3', '2'),
('4', '3'),
('5', '4'),
('6', '5'),
('7', '6'),
)
course_code = models.CharField(max_length=20, default="CSE-101", unique=True)
course_name = models.CharField(max_length=50, default="C Language", unique=True)
course_credit = models.CharField(max_length=1, choices=Credits, default='4')
def __str__(self):
return self.course_code
class Student(models.Model):
std_name = models.CharField(max_length=40)
std_id = models.CharField(max_length=50, primary_key=True)
std_email = models.EmailField(max_length=50, unique=True, blank=True)
course = models.ManyToManyField(Course)
def __str__(self):
return self.std_id
when i input data in Student table, database create a table student_course, i want to get this student_course data.
I want to get data each student how many course they registered and each course name. How can i get this data and show this data in webpage?
I'm a noob to python and Django so any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想获取此 Student_course 数据
->要从学生表访问相关对象,您可以像这样访问Student.course.all()
我想获取每个学生注册了多少门课程以及每门课程的数据名称
->您可以通过过滤 Student 对象来检索每个学生的课程,如下更新
如果您想为所有用户获取课程,您必须这样做,
如果您想在模板中重新渲染课程,请这样
做 views.py
studentlist.html 中的
i want to get this student_course data
-> to access related object from student table you can access like thisStudent.course.all()
I want to get data each student how many course they registered and each course name
-> You can retrieve courses of each student by filtering Student object like thisUpdate
If you want to get courses for all users you've to do like this
if you want to reder courses in template do like this
in you views.py
in your studentlist.html
您好,如果您想为每个学生提供课程,此代码可以帮助您:
hi if you want to get courser per student this code can help you: