Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django association between three models

I have these three models :

  • Person.
  • Project.
  • Role.

Using Django's models system, how to represent the fact that a person is participating in a particular project with a specific role ?

general problem : What is the proper way to handle "ternary associations" using Django ?

like image 365
user2080105 Avatar asked Oct 29 '22 15:10

user2080105


1 Answers

I would do it using an intermediary model for m2m relationship and add a field there.
Something like this:

class Role(models.Model):
    name = models.CharField(max_lenth=32)

class Project(models.Model):
    name = models.CharField(max_lenth=32)

class PersonProject(models.Model):
    person = models.ForeignKey('.Person')
    project = models.ForeignKey(Project)

    role = models.ForeignKey(Role)

class Person(models.Model):
    projects = models.ManyToManyField(Project, through=PersonProject)
like image 152
wanaryytel Avatar answered Nov 27 '22 07:11

wanaryytel