Home > database >  How to make more than one fields primary key and remove auto generated id in django models
How to make more than one fields primary key and remove auto generated id in django models

Time:09-21

Suppose in a relational database schema we have a student, a subject and a teacher which connect to each other with a relation teaches. Also, the relation has an attribute time that stores the time of the lesson. This is the most complete yet simplified example I can think to describe my case. Now, the most pythonic and django-wise way I can think of trying to reach a correct solution is, after creating a model class for student, subject and teacher, to create a new class Teaches, which has the foreign keys for the three other classes; also it has the property date field for time. This class would look something like this:

class Teaches(models.Model):
    teachers = models.ForeignKey(Teacher, on_delete_models.CASCADE)
    subjects = models.ForeignKey(Subject, on_delete_models.CASCADE)
    students = models.ForeignKey(Student, on_delete_models.CASCADE)
    time = models.DateField

    class Meta:
        constraints = [
            fields=['teachers', 'subjects', 'students']
            name='teacher_subject_student_triplet'
        ]

I added the Meta class because this is what enter image description here

  • Related