Django多级模型访问

时间:2018-10-09 08:22:24

标签: python django django-models django-rest-framework

我想执行以下操作:

  1. 我想注册一个学生参加课程
  2. 我想根据学生的注册情况为其输入课程分数
  3. 我想计算学生在他注册的每门课程中的总成绩

模型设计:   https://i.stack.imgur.com/8xLys.jpg

学生模型:

class Student(models.Model):
    name = models.CharField(max_length=50)
    rollno = models.CharField(max_length=50)
    department = models.ForeignKey('academic.Department', on_delete=models.DO_NOTHING, related_name= 'student')
    programme = models.ForeignKey('academic.Programme', on_delete=models.DO_NOTHING, related_name='registeredstudent')
    class Meta:
       verbose_name = 'Student'
       verbose_name_plural = 'Students'

   def __str__(self):
        return self.name

课程模型

class Course(models.Model):
        name = models.CharField(max_length=50)
        code = models.CharField(max_length=50)
        finternal = models.IntegerField()
        fexternal = models.IntegerField()
        ftotal = models.IntegerField()
        credit = models.IntegerField()

     class Meta:
          verbose_name = 'Course'
          verbose_name_plural = 'Courses'


     def __str__(self):
          return self.name

课程注册模型

class CourseRegistration(models.Model):
     student = models.ForeignKey('student.Student',on_delete=models.CASCADE, related_name='courseregistration')
     course = models.ForeignKey('academic.Course', on_delete=models.DO_NOTHING, related_name='courseregistration')


     class Meta:
        verbose_name = 'Course Registration'
         verbose_name_plural = 'Course Registrations'

CourseScore模型

class CourseScore(models.Model):
       student = models.ForeignKey('student.Student',on_delete=models.CASCADE, related_name='coursesore')
       course = models.ForeignKey('academic.Course', on_delete=models.DO_NOTHING, related_name='courseScore')
       courseregistration = models.ForeignKey('academic.CourseRegistration', on_delete=models.DO_NOTHING, related_name='courseScore')
       internal = models.IntegerField()
       external = models.IntegerField()
      total = models.IntegerField()


      def calculate_total(self):
      self.full = self.internal+self.external

结果模型

class Result(models.Model):
exam = models.ForeignKey('exams.Examination', on_delete=models.CASCADE, related_name='result')
student = models.ForeignKey('student.Student',on_delete=models.CASCADE, related_name='result')

total = models.IntegerField()
result = models.CharField(max_length=50)

class Meta:
    verbose_name = 'Result'
    verbose_name_plural = 'Results'

def __str__(self):
   return self.student

def save(self, *args, **kwargs):
    #result processing function
    #using the student foreign key  to select the courses 
    #using the exam foreign key to select the exam   
   super(Result, self).save(*args, **kwargs) # Call the real save() method

0 个答案:

没有答案