Django从抽象类访问子类项

moe*_*nad 6 python django

class Animal(models.Model):
    ....
    class Meta:
        abstract = True

class Cat(models.Model, Animal):
    ...

class Dog(models.Model, Animal):
    ....
Run Code Online (Sandbox Code Playgroud)

我希望能够返回Animal的所有子类的所有查询集实例.假设我有一个函数调用allData,它返回所有子类查询集的数组/列表.

例如:

x = animal.allData()[0] # should return the first element in the array.
Run Code Online (Sandbox Code Playgroud)

我不介意我们如何做到这一点,使用django-model-utils或不使用模块.我只是想能够返回所有子类查询集.

Gam*_*iac 16

这在一个查询中是不可能的.您有两个选项,一个用于使用django-model-utils或您可以使用django_polymorphic.

Polymorphic更适合你的任务,但是django-model-utils由django社区的一个非常杰出的成员制作,因此有很多好的支持.

如果我必须选择,我会选择django-model-utils由django团队成员制作,因此将得到支持.Divio支持多态,这是一家私人公司,大量使用瑞士的django.

至于如何选择子类.你需要做两件事django-model-utils.首先,您需要将objects模型中的变量更改为InheritanceManager()类似(根据文档改编):

from model_utils.managers import InheritanceManager

class Place(models.Model):
    # ...
    objects = InheritanceManager()

class Restaurant(Place):
    # ...

class Bar(Place):
    # ...

nearby_places = Place.objects.filter(location='here').select_subclasses()
for place in nearby_places:
    # "place" will automatically be an instance of Place, Restaurant, or Bar
Run Code Online (Sandbox Code Playgroud)

上面的代码将返回所有Bars和Restaurants,因为它使用了select_subclasses.

  • 它真的适用于抽象模型吗?我尝试在我的项目中实现它,这行`queryset = MyAbstractModel.objects.select_subclasses()`导致错误`AttributeError:Manager不可用; MyAbstractModel是抽象的"你知道为什么它对我不起作用吗? (3认同)