Home > Net >  Using django form many to many relationship model
Using django form many to many relationship model

Time:11-13

I am quite new to using Django, but basically I have two models: Student and Module

class Student(models.Model):
     student_id = models.CharField(max_length=4, unique=True)
     name = models.CharField(max_length=150)
     birthday = models.DateField()

class Module(models.Model):
     name = models.CharField(max_length=150)
     code = models.IntegerField()
     student = models.ManyToManyField(Student)

Now my question is, basically if I am using a Django form to add new students to the DB, how do I get the list of Modules I have in the DB.

I can add students to the module for adding a new module form, but not sure how to do it the other way

And say if I want to list all the modules a student is taking in a page, how do I access the modules those students are access to aswell?

Any help is much appreciated

CodePudding user response:

There are many ways to accomplish the task. But as the more professional practice is to redesign the DB schema so that you don't any duplication of data in database as elaborated below.

class Student(models.Model):
     student_id = models.CharField(max_length=4, unique=True)
     name = models.CharField(max_length=150)
     birthday = models.DateField()

class Module(models.Model):
     name = models.CharField(max_length=150)
     code = models.IntegerField()

class StudentsModule(models.Model):
     student = models.ForeignKey(Student)
     module = models.ForeignKey(Module)

Explaination

If you have list of users and want to add in the Module than you need to get list of Students(pk) from Student Model.

Create new Module and get the pk of Module.

You have list of Students and Module, Now You need to create records in StudentsModule Model. Create new row for each Student with Module.

Example

Create Students

  student_object1 = Student.objects.create(name="abc", birthday="2001-12-12")

  student_object2 = Student.objects.create(name="xyz", birthday="2005-12-12")

Create Module

  module_object = Module.objects.create(name="mno", code=123)

Create StudentsModule

  StudnetsModule.objects.create(student=student1, module=module_object)
  StudnetsModule.objects.create(student=student2, module=module_object)

Now you can access the list of Modules related with Student and the Students related to Module

CodePudding user response:

how do I get the list of Modules I have in the DB.

Module.objects.all()

how do I access the modules those students are access to aswell?

s = Student.objects.get(pk=1)
students_modules = s.module_set.all()
  • Related