Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Handle conditional prefetch related based on sparse field parameters#1276

jokiefer started this conversation inIdeas
Discussion options

Status quo
Currently theget_queryset simply adopted the definedprefetch_related andselect_related definitions. But there are still some existing bottlenecks:

Scenario: No include parameter
Given is: The used serializer has aResourceRelatedField and no include parameter is used.
For that case no predefiniedprefetch_related definition is used.
But theResourceRelatedField needs allids from the relation, so it will trigger the db to get it.

Solution: No include paramter
My current solution is to define conditionalprefetch_related definitions inside theget_queryset() on myviews.
Something like

defget_queryset(self):qs=super().get_queryset()include=self.request.GET.get("include",None)ifnotincludeor"fieldName"notininclude:qs=qs.prefetch_related(Prefetch("field_name",queryset=Model.objects.only('id'))returnqs

Without theprefetch_related definition it leads into the describedm*(n+1) problems

But there is another point. The code below prefetches in any case. But if the api is called withsparse fieldsets and the related field is not part of the request, the prefetching is not needed.

So it need another logic to get the fields parameters and analyze them against the prefetching logic. Something like:

fields=self.request.GET.get("fields[ResourceName]","").split(',')iffieldsand"fieldName"infields:# do prefetchingelse:# do not add default prefetching

So i think this is a general problem which hits every view with aResourceRelatedField, for that it would be worth it to add some logic to the core package to handle this.

You must be logged in to vote

Replies: 1 comment

Comment options

Thanks for bringing this up again. Indeed the prefetching implementation does not cover all use cases. There has been a discussion at#921 about it and also an attempt to implement it at#964 but got never finished. I am very open for improvements in this area but to get this right we most likely need a different approach as suggested in the above discussion than the two mixins we already have for this.

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Ideas
Labels
None yet
2 participants
@jokiefer@sliverc

[8]ページ先頭

©2009-2025 Movatter.jp