Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 386
TheCatParty Avatar asked Feb 23 '16 16:02

TheCatParty


1 Answers

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

Vegetable.objects.exclude(cucumber__isnull=True)
like image 68
ilse2005 Avatar answered Oct 31 '22 10:10

ilse2005