pythondjangoinheritancedjango-model-utils

Django-model-utils Filter By Subclass


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!


Solution

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

    Vegetable.objects.exclude(cucumber__isnull=True)