[Django]-Django, polymorphism and N+1 queries problem

1👍

Ok, I’ve digged a little bit further and found this nice passage:

https://github.com/bconstantin/django_polymorphic/blob/master/DOCS.rst#performance-considerations

So happily this library does something reasonably sane. That’s good to know.

👤julx

2👍

Django-Typed-Models is an alternative to Django-Polymorphic which takes a simple & clean approach to solving the single table inheritance issue. It works off a ‘type’ attribute which is added to your model. When you save it, the class is persisted into the ‘type’ attribute. At query time, the attribute is used to set the class of the resulting object.

It does what you expect query-wise (every object returned from a queryset is the downcasted class) without needing special syntax or the scary volume of code associated with Django-Polymorphic. And no extra database queries.

👤rcoup

1👍

In Django inherited models are internally represented through an OneToOneField. If you are using select_related() in a query Django will follow a one to one relation forwards and backwards to include the referenced table with a join; so you wouldn’t need to hit the database twice if you are using select_related.

Leave a comment