[Answer]-Filter prefetch_related and select_related results

1👍

Since you want to Get a Book with a specific BookTranslation, so its better that you base your Query on BookTranslation and get the Book object from it.

i.e. Use something like this

class BookDetail(DetailView):
    model = Book

    def get_object(self):
        self.booktranslation = BookTranslation.objects.select_related('book').get(book__slug=self.kwargs['slug'],
                                     language=self.kwargs['language'])
        return self.booktranslation.book

You can then pass self.booktranslation as a context variable to access that in template.

0👍

You can try something like this to hit the database only once and fetch the related results:

class BookDetail(DetailView):
    model = Book

    def get_object(self):
        return self.model.objects.filter(slug=self.kwargs['slug'],
                                         translations__language=self.kwargs['language'],
                                         translations__chapter__name=self.kwargs['ch_name'], ) \
                                 .values('translations__language',
                                         'translations__another_field', 
                                         'translations__chapter__name',
                                         'translations__chapter__another_field', )[0]

Leave a comment