Model inheritance in Django
a.k.a. "How to query for all objects not in a given subclass"
I ran across this problem today - do please leave a comment if you know of a better way to solve it than what follows.
You have two Django models, one of which inherits from the other, e.g.:
class Order(models.Model): # some fields class DiningOrder(Order): # some more fields
So, how do I write a query (using the Django ORM) which returns all the Orders which are not DiningOrders?
Apparently, this does the trick:
>>> Order.objects.all().count() 762L >>> DiningOrder.objects.all().count() 93L >>> Order.objects.exclude(id__in=[d.id for d in DiningOrder.objects.all()]).count() 669L