Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-polymorphic Filter by child type

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!

like image 338
lukaszzenko Avatar asked Mar 26 '14 23:03

lukaszzenko


1 Answers

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))
like image 159
knbk Avatar answered Nov 19 '22 22:11

knbk