`select_related` and `prefetch_related`
See original GitHub issueWhen 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/orselect_related
when such fields are present in graph queries.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:76
- Comments:32 (8 by maintainers)
Top Results From Across the Web
Prefetch_related and select_related functions in django
select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. · prefetch_related() ...
Read more >python - What's the difference between select_related and ...
The difference is that select_related does an SQL join and therefore gets the results back as part of the table from the SQL...
Read more >Django select_related and prefetch_related | by Goutom Roy
In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects.
Read more >QuerySet API reference | Django documentation
Django provides a range of QuerySet refinement methods that modify either the types of results returned by the QuerySet or the way its...
Read more >select_related and prefetch_related in Django - Javatpoint
When we fetch any object from the database, it returns the new queryset consists of that object not a particular object. It will...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Hi all! I’ve been working on a library that tries to optimize the query by analyzing the gql query:
https://github.com/tfoxy/graphene-django-optimizer
Feel free to open issues if your use case doesn’t work.
it would make sense reopening this