Skip to content

Instantly share code, notes, and snippets.

@Finndersen
Last active August 29, 2023 12:53
Show Gist options
  • Save Finndersen/3a9647718b35d6776b0dc3808a501519 to your computer and use it in GitHub Desktop.
Save Finndersen/3a9647718b35d6776b0dc3808a501519 to your computer and use it in GitHub Desktop.
PolymorphicRelatedQuerySet which allows select_related() to return polymorphic child models instead of base model
@matthew-nm
Copy link

I can't seem to get this code working for a situation where I have a StandardModel, a PolymorphicBaseModel (related to standard model on related_name "myrelation"), and multiple PolymorphicChildren.

I only work with the Children models, so when I have my StandardModel, I would like to be able to do StandardModel.objects.get(id=1).select_polymorphic_related("myrelation") and have it grab all the various Children with their appropriate attributes and models instead of the default of returning PolymorphicBaseModels with incomplete attributes and methods.

I managed to get your code above partially implemented, but it kept running into various issues that I was unable to parse.

Is the desired scenario I described something this code can do, or does it need some tweaks?

Thanks for any help you can provide!

@Finndersen
Copy link
Author

I can't seem to get this code working for a situation where I have a StandardModel, a PolymorphicBaseModel (related to standard model on related_name "myrelation"), and multiple PolymorphicChildren.

I only work with the Children models, so when I have my StandardModel, I would like to be able to do StandardModel.objects.get(id=1).select_polymorphic_related("myrelation") and have it grab all the various Children with their appropriate attributes and models instead of the default of returning PolymorphicBaseModels with incomplete attributes and methods.

I managed to get your code above partially implemented, but it kept running into various issues that I was unable to parse.

Is the desired scenario I described something this code can do, or does it need some tweaks?

Thanks for any help you can provide!

Is the problem perhaps because you are doing .get() before .select_polymorphic_related()? Try the other way around

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment