How to create a triple-join table with Django

后端 未结 4 1476
走了就别回头了
走了就别回头了 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条回答
  •  深忆病人
    2021-02-14 11:55

    I'd recommend just creating an entirely separate model for this.

    class Assignment(Model):
        user = ForeignKey(User)
        role = ForeignKey(Role)
        event = ForeignKey(Event)
    

    This lets you do all the usual model stuff, such as

    user.assignment_set.filter(role__name="Chaperon")
    role.assignment_set.filter(event__name="Silly Walkathon")
    

    The only thing left is to enforce your one-role-per-user-per-event restriction. You can do this in the Assignment class by either overriding the save method (http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods) or using signals (http://docs.djangoproject.com/en/dev/topics/signals/)

提交回复
热议问题