From 5e8ebef5b17f1a0f4110de61bd6d891b288adfb6 Mon Sep 17 00:00:00 2001 From: Matthew Schinckel Date: Fri, 16 May 2014 20:23:04 +0930 Subject: [PATCH] Add ability to filter an InheritanceQuerySet by model. This is based upon the feature in django-polymorphic, where you can do: SuperClass.objects.instance_of(SubClass) This will result in only objects of the subclass being fetched. Note: this works with any queryset, keeping the filtering and ordering applied there. --- model_utils/managers.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/model_utils/managers.py b/model_utils/managers.py index 0028f84..bcd0ef8 100644 --- a/model_utils/managers.py +++ b/model_utils/managers.py @@ -170,6 +170,14 @@ class InheritanceQuerySetMixin(object): levels = 1 return levels + def instance_of(self, model): + parent_field = model._meta.parents.values()[0].attname + query = '"%s"."%s" IS NOT NULL' % ( + model._meta.db_table, + parent_field + ) + return self.extra(where=[query]) + class InheritanceManagerMixin(object): use_for_related_fields = True @@ -184,6 +192,8 @@ class InheritanceManagerMixin(object): def get_subclass(self, *args, **kwargs): return self.get_queryset().get_subclass(*args, **kwargs) + def instance_of(self, model): + return self.get_queryset().instance_of(model) class InheritanceQuerySet(InheritanceQuerySetMixin, QuerySet): pass