0

I have the following (simplified) database model, where I refer to users of the application as "teacher":

class Student(models.Model):
    teacher = models.ForeignKey('auth.User', related_name="students")
    name = models.TextField()

class Task(models.Model):
    teacher = models.ForeignKey('auth.User', related_name="tasks")
    description = models.TextField()

class Grade(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    grade =  models.FloatField()

How do I ensure that the grade belongs only to one teacher? Or is there another way to improve my model?

Thanks

edit: I just found another SO question that answers a similar question: In django, how to limit choices of a foreignfield based on another field in the same model?

Am I right, that I "have to ensure it at the input"?

Community
  • 1
  • 1
asPlankBridge
  • 1,032
  • 1
  • 17
  • 30

3 Answers3

1

Try Django Smart Selects we use them in our project to solve that exact problem

Daniele Bernardini
  • 1,516
  • 1
  • 12
  • 29
0

You can try to find a workaround with unique_together (https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together) by overriding it for your special needs.

But it might not be easy: Django Unique Together (with foreign keys)

But it's never wrong to check values before insert ;-)

Community
  • 1
  • 1
zypro
  • 1,158
  • 3
  • 12
  • 33
0

Maybe teacher should be a separate class, and teacher in Task class should be related with teacher from Student class. Maybe usage the through argument is option for it.