On Sat, May 9, 2015 at 4:15 PM, Tim Chase
<
django...@tim.thechases.com> wrote:
> Since people can attend multiple schools and work for multiple
> employers, you can just make it a many-to-many, using the stock
> auth User:
>
> from django.contrib.auth.models import User
>
> class Company(models.Model):
> ...
>
> class School(models.Model):
> ...
>
> class Employee(models.Model):
> company = models.ForeignKey(Company)
> employee = models.ForeignKey(User)
>
> class Student(models.Model):
> school = models.ForeignKey(School)
> employee = models.ForeignKey(User)
>
This would just be explicitly defining the join or through tables used
for a M2M relationship, and is unnecessary if you are not adding
fields to the join table - Django can infer those tables for itself.
If you aren't adding an extra information to the join table, it would
still be better to specify them as a ManyToManyField, so that django
can provide a few extra bits of magic.
Django does not care what model you place the M2M relation on, so
without modifying the stock User model...
class Company(models.Model):
employees = models.ManyToManyField(User)
class School(models.Model):
students = models.ManyToManyField(User)
If you then wanted to define extra attributes on the relationship, eg
for a student, date started or date left...
class Student(models.Model):
school = models.ForeignKey(School)
user = models.ForeignKey(User)
enrolled_date = models.DateField(blank=True, null=True)
graduation_date = models.DateField(blank=True, null=True)
class School(models.Model):
students = models.ManyToManyField(User, through=Student)
etc
It is always worth defining that a join table is part of a M2M
relationship, eg with a School and a User, you could do:
some_school.students.add(some_user)
Without defining it as a M2M relationship, you would have to say:
Student.objects.create(school=some_school, user=some_user)
which not only is less clear, but is also more typing!
Cheers
Tom