Filtering plain models on their relation to a subclass of a django polymorphic model?
<p>I have a plain Django model that has a ForeignKey relation to a django-polymorphic model. </p>

<p>Let's call the first <code>PlainModel</code> that has a <code>content</code> ForeignKey field to a polymorphic <code>Content</code> model with subtypes <code>Video</code> and <code>Audio</code> (simplified example).</p>

<p>Now I want to query for all <code>PlainModel</code> instances that refer to a <code>Video</code>.</p>

<p>Problem is all the docs I find are about filtering directly via the polymorphic model itself. So in this example something like <code>Content.objects.instance_of(Video)</code>. But I need <code>PlainModel</code>'s, so it would need to look something like <code>PlainModel.objects.filter(content__instance_of=Video)</code>. I tried a bunch of variations but I cannot find anything that works. </p>

<p>In the docs they use <code>Q(instance_of=ModelB)</code>, but this doesn't work on the relation as <code>Q(content__instance_of=ModelB)</code>. It gives an error like 'Cannot query "x": Must be "y" instance.' even with the translation call, I guess because the PlainModel is not polymorphic aware.</p>

<p>I have a temporary hack that directly filters on the <code>polymorphic_ctype</code> field using regular django filter like <code>PlainModel.objects.filter(content__polymorphic_ctype_id=my_content_type_id)</code>, but this doesn't handle subclasses. Eg: <code>ExtendedVideo</code> would not be found when looking for <code>Video</code>, because it would have a different ContentType id. </p>

<p>I could go solve this and keep a list of allowed subtypes or parse the type hierarchy to get more content types for the filter but that seems to duplicating functionality from django-polymorphic.</p>

<p>You can do this by first getting all the <code>PlainModel</code> instances that have a <code>Video</code> subtype, and then querying for the foreign key relationships that are in that queryset:</p>

<pre><code>content_videos = Content.objects.instance_of(Video)
plain_model_videos = PlainModel.objects.filter(content__in=content_videos)
</code></pre>

<p>Please see <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#in" rel="nofollow">the docs</a> for reference.</p>

python django django-polymorphic