I have a query which takes too much time to load can I enhance it with prefetch_related(Prefetch()). My code is below:
class Detail_View(DetailView):
model = Detail
template_name = "apps/detail.html"
def get_context_data(self, **kwargs):
context = super(Detail_View, self).get_context_data(**kwargs)
detail = Detail.objects.get(pk=self.get_object().id)
detail.views +=1
detail.save()
DViews.objects.create(detail_id=self.get_object().id)
detail_set = self.model.objects.prefetch_related('favourite', 'categories', 'parody', 'characters','tags','groups','artists','relationship','languages', 'images_set').filter(categories__in=self.get_object().categories.all())
context['detail_list'] = detail_set.exclude(id=self.get_object().id).order_by('title').distinct()[:5]
context['images'] = [image.full_image.url for image in detail.fullimages_set.order_by('id').exclude(Q(full_image='')|Q(full_image='sample/sample-picture.png'))]
return context
def get(self, request, *args, **kwargs):
if not self.kwargs['slug']:
return redirect('detail_detail', self.get_object().pk, slugify(self.get_object().title)[:25])
if not self.get_object().all_detail_images.count():
return HttpResponseRedirect(reverse('index'))
return super(Detail_View, self).get(request, *args, **kwargs)