Combine queries from 2 inherited Django models

315 Views Asked by At

I would like to perform a prefetch. The point is: I have a baseModel and inherited models that are liked to other models. But my baseModel isn't linked with them. Here is the speudo code:

class Author(models.Model):
    name = models.CharField()

class Movie(PolymorphicModel):
    title = models.CharField()
    author = models.ForeignKey('Author')

class EnglishMovie(Movie):
    pass

class FrenchMovie(Movie):
    pass

class Subtitle(models.Model):
    movie = models.ForeignKey('FrenchMovie', related_name='subtitle')
    text = models.CharField()

As you can see, FrenchMovie is linked to subtitles, but EnglishMovie isn't. I would like to prefetch all my movie, and prefetch the subtitles as well. I've tried several methods:

def get_queryset(self):
    return Movie.objects.prefetch_related('author', 'subtitle').all()

I get: ValueError: Cannot query "EnglishMovie object (1)": Must be "FrenchMovie" instance.

def get_queryset(self):
    q1 = Movie.objects.prefetch_related('author').all()
    q2 = FrenchMovie.objects.prefetch_related('subtitle').all()
    return q1 | q2

I get: AssertionError: Cannot combine queries on two different base models.

Any tips ? Thanks a lot.

0

There are 0 best solutions below