How to query abstract-class-based objects in Django?

At its root, this is part of the mismatch between objects and relational databases. The ORM does a great job in abstracting out the differences, but sometimes you just come up against them anyway.

Basically, you have to choose between abstract inheritance, in which case there is no database relationship between the two classes, or multi-table inheritance, which keeps the database relationship at a cost of efficiency (an extra database join) for each query.


You can't query abstract base classes. For multi-table inheritance you can use django-model-utils and it's InheritanceManager, which extends standard QuerySet with select_subclasses() method, which does right that you need: it left-joins all inherited tables and returns appropriate type instance for each row.


Don't use an abstract base class if you need to query on the base. Use a concrete base class instead.


This is an example of polymorphism in your models (polymorph - many forms of one).

Option 1 - If there's only one place you deal with this:

For the sake of a little bit of if-else code in one or two places, just deal with it manually - it'll probably be much quicker and clearer in terms of dev/maintenance (i.e. maybe worth it unless these queries are seriously hammering your database - that's your judgement call and depends on circumstance).

Option 2 - If you do this quite a bit, or really demand elegance in your query syntax:

Luckily there's a library to deal with polymorphism in django, django-polymorphic - those docs will show you how to do this precisely. This is probably the "right answer" for querying straightforwardly as you've described, especially if you want to do model inheritance in lots of places.

Option 3 - If you want a halfway house:

This kind of has the drawbacks of both of the above, but I've used it successfully in the past to automatically do all the zipping together from multiple query sets, whilst keeping the benefits of having one query set object containing both types of models.

Check out django-querysetsequence which manages the merge of multiple query sets together.

It's not as well supported or as stable as django-polymorphic, but worth a mention nevertheless.