使用多对多字段
class Student(models.Model):
name = models.CharField(...)
attendance = models.ManyToMany(Subject)
class Subject(models.Model):
subject = models.CharField(...)
会是这样的
id | student_id | subjects_id
-----------------------------------------
1 | 1 | 10
2 | 4 | 11
3 | 4 | 19
4 | 5 | 10
...
~1000
每个学生都有多个科目...而多个科目可以来自我的学生
Obs.:通常我想将我的 ManyToMany 关系称为复数形式的第二个表的名称......所以主题
用法:
all_students = Student.objects.all()
all_subjects = Subject.objects.all()
all_subjects_from_student = Student.objects.get(id=1).attendance.all()
我将如何标记特定学生的出勤情况
特定主题?
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/
编辑如果您在出勤时需要任何新字段,您也可以在不使用多对多的情况下这样做
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
这里有一个和你一样的问题:django accessing raw many to many created table fields