我有基类Publication
,Book
和Magazine
继承自。{1}}。
class Author(models.Model):
pass
class Publication(models.Model):
author = models.ForeignKey(Author)
class Book(Publication):
pass
class Magazine(Publication):
pass
我想找到某个作者的所有Book
和Magazine
个对象。由于Author
的外键位于父类Publication
上,因此我对查询的尝试都返回Publication
个对象而不是子类:
# Both of these return Publication objects, not Book/Magazine objects
Author.objects.get(pk=1).publication_set
Publication.objects.get(author_pk=1)
是否有办法获取具有特定作者的所有子类实例,而无需为Book.objects.get(author_pk=1)
之类的所有子类手动运行查询(实际上我有两个以上的子类)?
答案 0 :(得分:0)
您可能需要使用外部程序包来获得此类功能。这看起来像你需要的:https://django-model-utils.readthedocs.io/en/latest/managers.html#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