查找匹配查询的子模型的所有实例

时间:2016-09-12 16:46:38

标签: django django-models

我有基类PublicationBookMagazine继承自。{1}}。

class Author(models.Model):
   pass

class Publication(models.Model):
   author = models.ForeignKey(Author)

class Book(Publication):
   pass

class Magazine(Publication):
   pass

我想找到某个作者的所有BookMagazine个对象。由于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)之类的所有子类手动运行查询(实际上我有两个以上的子类)?

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