0

My model contains 3 classes.

class Student(models.Model):
    name = models.CharField(...)
class Subject(models.Model):
    subject = models.CharField(...)

class Attendance(Student, Subject):
    att = model.IntegerField()

Now, I want to create an attendance table for each Subject of each Student. Therefore I don't want to fill Subject and Student details for every subject and student again. Please tell me an optimal way of doing this so that at the admin panel I just want to add each subject and student only once.

There may be multiple students studying a subject and there may also be multiple subjects for a student.

(You may tell me another way of doing this instead of inheriting Student and Subject).

Dev Pahuja
  • 35
  • 8

1 Answers1

1

Use ManyToManyField

class Student(models.Model):
    name = models.CharField(...)
    attendance = models.ManyToMany(Subject)    

class Subject(models.Model):
    subject = models.CharField(...)

This will be like that

id   |    student_id   |  subjects_id
-----------------------------------------
1    |    1            |  10
2    |    4            |  11
3    |    4            |  19
4    |    5            |  10
...
~1000

Each Student will have multiple Subjects... while multiple subjects can be from my students

Obs.: Usually i would like to call my ManyToMany relations the name of second table in plural... so subjects

Usage:

all_students = Student.objects.all()
all_subjects = Subject.objects.all()
all_subjects_from_student = Student.objects.get(id=1).attendance.all()

How would I mark the attendance of a particular student for a particular subject?

particular_student = Student.objects.get(id=1) # When 1 is the student ID
particular_subject_of_student = particular_student.filter(id=1) # When 1 is the subject ID

https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/

EDIT You can do that too without using ManyToMany, if you need any new field at Attendance

class Student(models.Model):
    name = models.CharField(...)

class Subject(models.Model):
    subject = models.CharField(...)

class Attendance(Student, Subject):
    att = models.IntegerField()
    subject = models.ForeignKey(Subject)
    student = models.ForeignKey(Student)
    ... # You can add more fields if you like

Here go one question like yours: django accessing raw many to many created table fields

Diego Vinícius
  • 2,125
  • 1
  • 12
  • 23