简体   繁体   中英

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!

如果您只想过滤Cucumber对象,您可以执行以下操作:

Vegetable.objects.exclude(cucumber__isnull=True)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM