graphql-python/graphene-django

`select_related` and `prefetch_related`

Open

#57 创建于 2016年11月13日

在 GitHub 查看
 (38 评论) (84 反应) (0 负责人)Python (4,173 star) (754 fork)batch import
help wantedwontfix📖 documentation

描述

When I inspected the actual SQL queries being run against DB, I found that for foreignkey and manytomany relationships, we have the n+1 problem.

For example, suppose there are 5 teams, each with 11 members, this query:

query {
  teams {
    edges {
      node {
        members {
          edges {
            node {
              name
            }
          }
        }
      }
    }
  }
}

will result in 1 query for selecting teams, and 5 more queries for selecting members of each team. 6 queries in total.

Normally, we would do a query like this Team.objects.all().prefetch_related('members') to reduce to 2 queries.

I think it would be extremely beneficial if DjangoObjectType can detect special fields:

  • ForeignField
  • OneToOneField
  • OneToManyField
  • ManyToManyField and apply appropriate prefetch_related and/or select_related when such fields are present in graph queries.

贡献者指南

`select_related` and `prefetch_related` · graphql-python/graphene-django#57 | Good First Issue