Django从抽象类访问子类项 [英] Django access to subclasses items from abstract class
问题描述
class Animal(models.Model):
....
class Meta:
abstract = True
class Cat(models.Model, Animal):
...
class Dog(models.Model, Animal):
....
我想能够返回Animal的所有子类的所有查询的实例。假设我有一个名为 allData
的函数,它返回所有子类查询集的数组/列表。
I want to be able to return all instances of querysets of all the subclasses of Animal. Lets say I have a function called allData
which returns an array/list of all the subclasses querysets.
例如:
x = animal.allData()[0] # should return the first element in the array.
我不介意我们这样做,使用模块,如 django- model-utils
。我只是希望能够返回所有的子类查询集。
I don't mind how we do this, using modules like django-model-utils
or not. I just want to be able to return all the subclasses querysets.
推荐答案
这在一个查询中是不可能的。您有两个选项,一个用于使用 django-model-utils
,或者您可以使用 django_polymorphic
。
This is not possible in one query. You have two options, one use to use django-model-utils
or you can use django_polymorphic
.
多形态更适合您的任务,但 django-model-utils
是由django社区的非常杰出的成员制作的,因此有很多好的支持。
Polymorphic is better suited to your task, however django-model-utils
is made by a very prominent member of the django community and as such has a lot of good support.
如果我不得不选择,我会选择 django-model-utilts 由于它是由django团队成员制作的,因此将得到支持。多形态由divio支持,Divio是一家在瑞士大量使用django的私人公司。
If I had to choose, I'd choose django-model-utilts
since its made by a member of the django team, and thus will be supported. Polymorphic is supported by divio, which is a private company that heavily uses django based in Switzerland.
至于如何选择子类。您需要使用 django-model-utils
做两件事情。首先,您需要将模型中的对象
变量更改为 InheritanceManager()
(从文档改编):
As for how to select Sub-classes. You need to do two things using django-model-utils
. Firstly, you need to change the objects
variable in your model to InheritanceManager()
like so (adapted from 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
上面的代码将返回所有 Bar
s和 Restaurant
s,因为它使用 select_subclasses
。
The code above will return all Bar
s and Restaurant
s because it uses the select_subclasses
.
这篇关于Django从抽象类访问子类项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!