Skip to content

Conversation

pgammans
Copy link

This pull request add support for select related and general related queries.

Summary
To take advantage of this it requires that the plain Django model either adds a custom query set manager and uses that for queries where it wants the related object to be transmogrify into the final polymorphic type of
that the default manager's queryset uses/ has PolymorphicQuerySetMixin or PolymorphicRelatedQuerySet as a base class

ie
class PlainModel(models.Model): objects = models.Manager.from_queryset(PolymorphicRelatedQuerySet)()

The default Django select_related can be used including which means this is simple to use from the Django admin.

Performance
When using select_related we archive fetch of the data in a single query including all information required to transmogrify the related object. This is an improvement from n+1 (main line) or models + 1 (with #531)

Notes

  • This make a small change to the accessor function on the model allowing the base object to be fetched form the cached
  • This commit has to copy segments of Django internal for it RelatedPopulator and ModelIterable as there are no hooks.

It has minimal support for prefetch_related cannot fetch attributes not on all child models or via class names this may fix #498

Fixes: #198 #436 #359 #244

@PetrDlouhy
Copy link
Contributor

@pgammans Thanks, this seems to be very useful improvement.
Could you please rebase the code so that the tests would run against the current master?

Also I thing part of this PR should be change of documentation to reflect this, e.g.: https://django-polymorphic.readthedocs.io/en/stable/advanced.html?highlight=select_related#restrictions-caveats

@pgammans pgammans force-pushed the select_and_prefetch_related branch from 5eb5e3e to 89ea07b Compare April 4, 2024 14:59
@pgammans pgammans force-pushed the select_and_prefetch_related branch from 94243ad to eae92aa Compare April 4, 2024 18:24
@alphatownsman
Copy link

it will be really nice to have this.

there seems to be some minor formatting issues in the latest commits. @pgammans would it be possible to fix them?

@Morfild
Copy link

Morfild commented Jul 27, 2024

Are you going to merge it one day?

@bvedad
Copy link

bvedad commented Aug 10, 2025

What is the status of this MR?

@bckohan bckohan self-assigned this Aug 11, 2025
@bckohan
Copy link
Contributor

bckohan commented Aug 11, 2025

pgammans

This is on the top of my list to review. Other reviews are also welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Prefetch's to_attr field is not respected for polymorphic models select_related and prefetch_related for inherited models
7 participants