Tuesday, December 22, 2015

Re: Django Model | Relationship question. Student->School Class

On Tue, Dec 22, 2015 at 6:50 AM, Pemby <briandanielz@gmail.com> wrote:
> 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?

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1LyMUkxqVnDBciMZv39fvg5Ly9H%2BLWgp63RRonYoxKZuQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment