How to create a triple-join table with Django

后端 未结 4 1491
走了就别回头了
走了就别回头了 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:53

    While trying to find a faster three-table join for my own Django models, I came across this question. By default, Django 1.1 uses INNER JOINs which can be slow on InnoDB. For a query like:

    def event_users(event_name):
        return User.objects.filter(roles__events__name=event_name)
    

    this might create the following SQL:

    SELECT `user`.`id`, `user`.`name` FROM `user` INNER JOIN `roles` ON (`user`.`id` = `roles`.`user_id`) INNER JOIN `event` ON (`roles`.`event_id` = `event`.`id`) WHERE `event`.`name` = "event_name"
    

    The INNER JOINs can be very slow compared with LEFT JOINs. An even faster query can be found under gimg1's answer: Mysql query to join three tables

    SELECT `user`.`id`, `user`.`name` FROM `user`, `roles`, `event` WHERE `user`.`id` = `roles`.`user_id` AND `roles`.`event_id` = `event`.`id` AND `event`.`name` = "event_name"
    

    However, you will need to use a custom SQL query: https://docs.djangoproject.com/en/dev/topics/db/sql/

    In this case, it would look something like:

    from django.db import connection
    def event_users(event_name):
        cursor = connection.cursor()
        cursor.execute('select U.name from user U, roles R, event E' \
                       ' where U.id=R.user_id and R.event_id=E.id and E.name="%s"' % event_name)
        return [row[0] for row in cursor.fetchall()]
    

提交回复
热议问题