Skip to content

Prefetch with optimize and only optimization enabled causes N+1ย #4250

@rcybulski1122012

Description

@rcybulski1122012

Describe the Bug

As the title says - if have the only optimization enabled and I optimize a queryset that is prefetched, it is going to cause N+1, problem because the id field that is used to matched the prefetch objects is excluded from the queryset.

Not sure if it's a bug or expected behaviour but I spend some time debugging it ๐Ÿ˜…. I solved the problem by disabling the only optimization, by passing the config instance to the optimize.

If it's not a bug I'd appreciate a more specific documentation on optimizer ๐Ÿ™

prefetched_fields: list[SomeFieldType] = strawberry_django.field(
    prefetch_related=lambda info: Prefetch(
      "some_fields",
      queryset=optimize(SomeField.objects.filter(...)),
      to_attr="prefetched_fields"
    )
)

System Information

  • Operating system: MacOs 14.8 (23J21)
  • Python version: 3.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions