Django similar queryset optimization


I am making a filmography website.
However, I am having a hard time optimizing the queryset in the detailview.

class Actor(model.Models):
    id = models.IntegerField()
    name = models.CharField()

class Movie(model.Models):
    id = models.IntegerField()
    movie_title = models.CharField()
    actor = models.ManyToManyField(Actor, related_name='relations')

class ActorView(DetailView):
    model = Actor
    context_object_name = 'actor'
    template_name = 'actor.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['movies'] = self.object.relations.all()
        return context

   {{ }}
   {% for movie in movies %}
       {{ movie.movie_title }}
       {% for actor_info in %}
       {{ }}
       {% endfor %}
   {% endfor %}

I checked the sql tap in the django debug console.

   {% for actor_info in %}
   {{ }}
   {% endfor %}

Similar queries are being executed repeatedly in the code above.
And data connection and query execution time are also very slow.
How can I optimize this part in the view or model?


You can speed this up using prefetch_related

So in your view, change this line from

context['movies'] = self.object.relations.all()


context['movies'] = self.object.relations.all().prefetch_related("actor")

Answered By – tushortz

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published