Django Model | Relationship question. Student->School Class

31 views
Skip to first unread message

Pemby

unread,
Dec 22, 2015, 1:50:12 AM12/22/15
to Django users
With this code for example.

    class Students(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        classChoice1 = ?
        classChoice2 = ?
        classChouce3 = ?   
   
    class Class(models.Model):
        class_name = models.CharField(max_length=30)
        class_discription = models.CharField(max_length=30)   


Say for example I have Nth students, S1 S2 S3 ... and Nth classes (as in college class) C1 C2 C3 ...
And I want to create a relationship where each student can only be assigned to one class uniquely for each classChoice
selected. How would I create that relationship?


Tom Evans

unread,
Dec 22, 2015, 6:07:44 AM12/22/15
to django...@googlegroups.com
Remove the classChoiceN fields from Students, and add a ManyToMany
between Student and Class (remember model class names should be
singular, so "Student", not "Students") using a through table with an
additional "choice" integer field.

The "choice" field should have a maximum value of 3, and you will want
unique_together constraints on the through table for (student, class)
and (student, choice) - you can't sign up for the same class twice,
and you can only have one of each choice.

Cheers

Tom
Reply all
Reply to author
Forward
0 new messages