class Animal(models.Model):
....
class Meta:
abstract = True
class Cat(models.Model, Animal):
...
class Dog(models.Model, Animal):
....我希望能够返回动物所有子类的所有查询集的所有实例。假设我有一个名为allData的函数,它返回所有子类queryset的数组/列表。
例如:
x = animal.allData()[0] # should return the first element in the array.我不介意我们如何使用像django-model-utils这样的模块。我只想返回所有的子类查询集。
发布于 2013-09-11 13:55:28
这在一个查询中是不可能的。您有两个选项,一个是使用django-model-utils,另一个是使用django_polymorphic。
多态更适合您的任务,但是django-model-utils是由django社区的一位非常杰出的成员制作的,因此有很多很好的支持。
如果我必须选择,我会选择django-model-utils,因为它是由django团队的一名成员制作的,因此将得到支持。divio支持多态,该公司是一家在瑞士大量使用django的私营公司。
关于如何选择子类。您需要使用django-model-utils做两件事。首先,您需要像这样将模型中的objects变量更改为InheritanceManager() (改编自docs):
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上面的代码将返回所有Bars和Restaurants,因为它使用select_subclasses。
发布于 2013-09-11 13:47:33
你可能对多态感兴趣
项目文档中的示例:
当我们存储继承自Project模型的模型时.
>>> Project.objects.create(topic="Department Party")
>>> ArtProject.objects.create(topic="Painting with Tim", artist="T. Turner")
>>> ResearchProject.objects.create(topic="Swallow Aerodynamics", supervisor="Dr. Winter")...and要检索我们的所有项目,将返回子类模型:
>>> Project.objects.all()
[ <Project: id 1, topic "Department Party">,
<ArtProject: id 2, topic "Painting with Tim", artist "T. Turner">,
<ResearchProject: id 3, topic "Swallow Aerodynamics", supervisor "Dr. Winter"> ]https://stackoverflow.com/questions/18742870
复制相似问题