Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a triple-join table with Django

Using Django's built in models, how would one create a triple-join between three models.

For example:

  • Users, Roles, and Events are the models.
  • Users have many Roles, and Roles many Users. (ManyToMany)
  • Events have many Users, and Users many Events. (ManyToMany)
  • But for any given Event, any User may have only one Role.

How can this be represented in the model?

like image 587
phloopy Avatar asked Sep 16 '08 14:09

phloopy


1 Answers

zacherates writes:

I'd model Role as an association class between Users and Roles (...)

I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: ManyToMany relation with extra fields.

Example:

class User(models.Model):
    name = models.CharField(max_length=128)

class Event(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(User, through='Role')

    def __unicode__(self):
        return self.name

class Role(models.Model):
    person = models.ForeignKey(User)
    group = models.ForeignKey(Event)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
like image 115
zuber Avatar answered Sep 29 '22 20:09

zuber