Desh
Desh

Reputation: 155

Complex prefetch_related

There is a request which returns a list of several Lists with their movies. I want to use prefetch to Lists to optimize db calls.

I have several models:

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

    class ListMovie(models.Model):
        list = models.ForeignKey(List)
        movie = models.ForeignKey(Movie)

    class Movie(models.Model): 
         title = models.CharField()
         other_fields... 

I have a separate prefetch for Movie to get other fields.

Is there a way to concatenate prefetch list of List objects with their movies and prefetch additional movie info?

Upvotes: 0

Views: 309

Answers (1)

ruddra
ruddra

Reputation: 51998

Sure, try like this:

List.objects.all().prefetch_related('listmovie__movie')

From updated question, as far as I know, you can't concatenate reverse relation objects with queryset. You can concatenate one object's field from all related objects using subquery. Like this:

from django.db.models import Subquery, OuterRef

newest = ListMovie.objects.filter(list=OuterRef('pk'))

List.objects.annotate(listmovie=Subquery(newest.values('pk')[0]))

Alternatively, you can use values queryset to show fields. For example:

 List.objects.values('listmovie').prefetch_related('listmovie__movie')

Upvotes: 1

Related Questions