Home > Net >  How can i get many to many relationship table data in django?
How can i get many to many relationship table data in django?

Time:02-27

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.

CodePudding user response:

i want to get this student_course data -> to access related object from student table you can access like this Student.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 this

student = Student.objects.get(std_id=_place_student_id_here_)
courses = student.course.all() # this will return all courses related to perticular student

Update

If you want to get courses for all users you've to do like this

students = Student.objects.all()
for student in students:
    print(student.course.all()) # this will return all courses for this student

CodePudding user response:

hi if you want to get courser per student this code can help you:

from models import Student

my_student = Student.objects.get(std_id = {student id})
student_course = my_student.course
totoal_course = student_course.count()
name_of_courses = [course.name for course in student_course.all()]
  • Related