blb-ventures / strawberry-django-plus

Enhanced Strawberry GraphQL integration with Django
MIT License
179 stars 47 forks source link

Optimise manually prefetched field #244

Open adammsteele opened 1 year ago

adammsteele commented 1 year ago

In this comment you say that we should be able to optimise the queryset of a manually prefetched field using optimize, however this does not appear to work.

The following code in the demo directory shows that the only optimisation is not applied to my_issues:

@gql.django.type(Milestone, filters=MilestoneFilter, order=MilestoneOrder)
class MilestoneType(relay.Node):
    name: gql.auto
    due_date: gql.auto
    project: ProjectType
    issues: List["IssueType"]

    @gql.django.field(
        prefetch_related=[
            lambda info: Prefetch(
                "issues",
                queryset=optimize(
                    Issue.objects.filter(
                        Exists(
                            Assignee.objects.filter(
                                issue=OuterRef("pk"),
                                user_id=info.context.request.user.id,
                            ),
                        ),
                    ),
                    info,
                ),
                to_attr="_my_issues",
            ),
        ],
    )
    def my_issues(self) -> List["IssueType"]:
        return self._my_issues  # type: ignore

    @gql.django.field
    async def async_field(self, value: str) -> str:
        await asyncio.sleep(0)
        return f"value: {value}"

Is it possible to use optimize in this way?

Thanks for the library!

bellini666 commented 1 year ago

Hey @adammsteele ,

Yes, it should indeed work (if it doesn't, then we have a bug =P)

You said that the only optimization is not working. But are the other optimizations working for it?