Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes: #11291
This optimizes the GraphQL queries by automatically putting in prefetch_related to queried fields. Results:
I made a bunch of VLANs and a query that shows the query issue resulting in a 10x or 20x reduction of queries, here are the query counts:
Tested with sample queries for nested types, nested filters, fragments (triple dot notation) and they all worked successfully.
Couple Notes on implementation:
There is some interaction between graphene / FilterSets and the optimizer. The optimizer works fine with graphene but without FilterSets and works fine outside of graphene with FilterSets, but combining Graphene, FilterSets and the optimizer produces extra queries. So netbox/netbox/graphql/fields.py if there are no filter params then it doesn't instantiate the FilterSet.
Propose this as a temporary solution as it results in 10x less queries in the non-filtered case and figuring out how to fix the interaction between graphql / filterset will be a big time sink I think so can create a separate issue for that.
There is a separate issue where this code: https://github.com/netbox-community/netbox/blob/develop/netbox/netbox/filtersets.py#L249 is adding in extra queries for custom-fields even if they are not referenced in the query-set. This is what causes the number of queries to double with the filtering at all levels feature that was added in NetBox 3.4. It isn't a bug in that feature, rather an existing bug that was just exposed by this change as it now applies filters at all levels in the schema. If the custom fields issue is fixed the querycount comes back down to 985 with filtering.
In the schmea files the lines:
were needed as unfortunately the optimizer code could not be put into fields.py which generically handles getting the schema class and filterset. The reason for this is two fold: