django-polymorphic Filter by child type

旧街凉风 提交于 2019-12-23 05:30:07

问题


I have models structure like below:

class MyObject(PolymorphicModel):
    group = models.ForeignKey(Group)

class Group(PolymorphicModel):
    pass

class SpecialGroup(Group):
    pass

Now, I would like to select all MyObjects, which group is of type SpecialGroup.

Is it possible to achieve it with QuerySet API, without running raw SQL? The only working solution I came up with was by running additional 'select' SQL query using .extra().

Thanks in advance, Cheers!


回答1:


Internally, django_polymorphic uses Django's ContentType framework to determine the actual class used for each model.

from django.contrib.contenttypes.models import ContentType

MyObject.objects.filter(group__polymorphic_ctype=ContentType.objects.get_for_model(SpecialGroup))


来源:https://stackoverflow.com/questions/22675596/django-polymorphic-filter-by-child-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!