A
A
AkiroToshiro2020-12-10 22:53:35
Django
AkiroToshiro, 2020-12-10 22:53:35

How to automatically create and add instances of one model to another?

I have two models, and when creating one, I want one of its fields to be automatically populated with instances of the other. Here's what I got:

class Grade(models.Model):
    value = models.CharField(max_length=3, blank=True)
    student_id = models.ForeignKey(Profile, blank=False)


class GradeBook(models.Model):
    group_id = models.ForeignKey(StudentsGroup, on_delete=models.CASCADE)
    date = models.DateField(blank=True)
    grade = models.ForeignKey(Grade, on_delete=models.SET_NULL)

    def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)

        get_students = Profile.objects.get.Filter(student_group=self.group_id).all()

        for student in get_students:
            new_grade = Grade(student_id=student.id)
            new_grade.save()

During the loop, you need to add new_grade.id to grade.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AkiroToshiro, 2020-12-10
@AkiroToshiro

Here's what I came up with, if anyone needs it. I did everything wrong from the very beginning, and when I realized everything went fine.

class GradeBook(models.Model):
    group_id = models.ForeignKey(StudentsGroup, on_delete=models.CASCADE)
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
    date = models.DateField(blank=False)


class Grade(models.Model):
    value = models.CharField(max_length=3, blank=True, default='')
    student_id = models.ForeignKey(Profile, blank=False, on_delete=models.CASCADE)
    gradebook = models.ForeignKey(GradeBook, on_delete=models.CASCADE, blank=False)


@receiver(post_save, sender=GradeBook)
def create_grades(sender, instance, created, **kwargs):
    if created:
       get_students = Profile.objects.all().filter(student_group=instance.group_id)

       for student in get_students:
           new_grade = Grade(student_id=Profile.objects.get(id=student.id), gradebook=instance)
           new_grade.save()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question