How to create a triple-join table with Django

后端 未结 4 1547
走了就别回头了
走了就别回头了 2021-02-14 11:25

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.
  • Us
4条回答
  •  萌比男神i
    2021-02-14 12:02

    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)
    

提交回复
热议问题