从模型获取所有相关数据,并使用django信号将其保存到另一个模型

时间:2019-11-04 00:42:20

标签: django

我只希望管理员在表学生注册记录中插入“课程”(ABM)和“教育程度”(11年级)和“科目”(编年史),它将在subjectsectionteacher(第二张图片)中获取所有相关数据,并将自动保存对于学生报名的科目(第三张图片),我的问题只是保存了一个数据。

student enrollment record

subjectsectionteacher

这就是我想要的结果

Result I want

这是我得到的结果

what I got result

class StudentsEnrolledSubject(models.Model):
    Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True)
    Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True)

@receiver(post_save, sender=StudentsEnrollmentRecord)
def create(sender, instance, created, **kwargs):
    teachers = SubjectSectionTeacher.objects.all().filter(Sections=instance.Section,Education_Levels=instance.Education_Levels)
    if created and teachers.exists():
            StudentsEnrolledSubject.objects.update_or_create(
            pk=instance.pk,
            # This should be the instance not instance.Student_Users
            Students_Enrollment_Records=instance,
            # The below is also not an instance of SubjectSectionTeacher
            Subject_Section_Teacher=teachers.first()

        )



class StudentsEnrollmentRecord(models.Model):
    Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE, null=True)
    School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True,
                                         null=True)
class SubjectSectionTeacher(models.Model):
    School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True)
    Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
    Sections = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True)
    Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True)

0 个答案:

没有答案