strawberry-django icon indicating copy to clipboard operation
strawberry-django copied to clipboard

prefetch_related and filtering in custom resolver

Open tasiotas opened this issue 8 months ago • 3 comments

I need to filter related models. Query optimizer works fine, but I cannot get it working with filtering inside custom resolver (without using @strawberry.django.filter)

  1. When I define my own Prefetch, I am getting double prefetch queries. One is mine, the other is from optimizer.
    @strawberry.django.field(
        prefetch_related=[
            lambda info: Prefetch(
                "downloadables",
                queryset=Downloadable.objects.filter(is_published=True).all(),
                to_attr="downloadables_prefetched",
            )
        ],
    )
    def downloadables(self) -> List[Annotated["DownloadableType", strawberry.lazy("vfxtricks.common.schema")]]:
        return self.downloadables_prefetched
  1. When I dont define my own Prefetch with custom name, then optimizer does make a Prefetch query, but query in my resolver does not take advantage of it. Meaning, I end up with way too many queries.
    @strawberry.django.field()
    def downloadables(self) -> List[Annotated["DownloadableType", strawberry.lazy("vfxtricks.common.schema")]]:
        return self.downloadables.filter(is_published=True)

thank you

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

tasiotas avatar Jun 15 '24 04:06 tasiotas