[Answer]-Django view foreign key in a backward relationship

1đź‘Ť

âś…

This is my recommend models

Groups

class Groups(models.Model):

    name    = models.CharField(max_length=200)
    description   = models.CharField(max_length=255, blank=True)


    def __str__(self):
        return self.name

Student Model

class Student(models.Model):

    name    = models.CharField(max_length=200, default='', blank=True)
    group   = models.ForeignKey(Groups, null=True, blank=True, unique=False)

    def __str__(self):
        return self.name

Code Model

class Code(models.Model):
     name = models.CharField(max_length=200)
     code = models.CharField(max_length=25)
     description = models.CharField(max_length=255)

def __str__(self):
    return self.name

Teacher Model

class Teacher(models.Model):
     name = models.CharField(max_length=200)
     code = models.ForeignKey(Code, unique=False)

def __str__(self):
    return self.name + " " + self.code.name

Sessions

class Sessions(Employe):
     teacher = models.ForeignKey(Teacher, unique=False)
     student = models.ForeignKey(Student, unique=False)
     session = models.IntegerField(null=True, blank=True)

def __str__(self):
    return self.teacher.name + ' ' + self.student.name

Now with “Sessions” will help you better manage, where session would contain a value
between 1-4 ( and possible more – imagine if you added an extra period to the day ). With teacher you will get a code, you can have multiple teachers with multiple codes, or the same teacher with multiple codes. I hope this gets you in the right direction and this in my opinion is a much cleaner way to approach this problem, let me know if you have any issues and I will add more details.

Leave a comment