Django-model-utils按子类过滤

时间:2016-02-23 16:17:22

标签: python django inheritance django-model-utils

我正在使用django-model-utils继承管理器来查询具有多表继承的数据模型,它的工作效果非常好!什么不好用的是我想要.select_subclasses()但也过滤特定的子类。例如:

class Salad:
    ...

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

class Cucumber(Vegetable):
    ...

class Carrot(Vegetable):
    ...

我希望能够只获得与特定Cucumber相关的所有Salad个对象,而不包含任何Carrot个对象。不幸的是,文档似乎没有解释这一点。在我保存任何可用于“常规”过滤的蔬菜对象时设置的type类上创建Vegetable字段是我的最佳选择吗?提前致谢!

2 个答案:

答案 0 :(得分:5)

如果您只想过滤arr= _.reject(arr, function(obj) { return obj.User.id == 768; }); 个对象,可以执行以下操作:

Cucumber

答案 1 :(得分:0)

您可以使用.select_subclasses(Cucumber)返回Cucumber个对象,其余为Vegetable个对象。您可以稍后使用isinstance

过滤掉它