Django-model-utils Filter By Subclass

1.7k Views Asked by At

I'm using django-model-utils inheritance manager to query a data model with multi-table inheritance and it mostly works great! What doesn't work great is when I want to .select_subclasses() but also filter for a specific subclass. For example:

class Salad:
    ...

class Vegetable:
    salad = models.ForeignKey(Salad)
    ...

class Cucumber(Vegetable):
    ...

class Carrot(Vegetable):
    ...

I would love to be able to just get ONLY all of the Cucumber objects related to a specific Salad without any Carrot objects. Unfortunately, the docs don't appear to explain this. Is my best option to create a type field on the Vegetable class that I set when saving any Vegetable object that would then be available for "regular" filtering? Thanks in advance!

2

There are 2 best solutions below

5
On BEST ANSWER

If you want to filter only Cucumber objects you could do something like this:

Vegetable.objects.exclude(cucumber__isnull=True)
1
On

You can use .select_subclasses(Cucumber) which would return the Cucumber objects and the rest as Vegetable objects. You could later filter it out using the isinstance