I have 3 models
models.py
class Book(models.Model):
name = models.CharField(max_length=255, primary_key=True)
...
class BookTranslation(models.Model):
book = models.ForeignKey(Book, related_name='translations')
language = models.CharField(max_length=2, choices=LANGUAGE_CHOICES)
...
class Chapter(models.Model):
book_translation=models.ForeignKey(BookTranslation,related_name='chapters')
...
I would like to create a DetailView for a book in just one language, my first approach was something like this:
views.py
class BookDetail(DetailView):
model = Book
def get_object(self):
return self.model.objects.select_related('translations').prefetch_related('translations__chapters').get(slug=self.kwargs['slug'], translations__language=self.kwargs['language'])
But this way i return all related BookTranslations and Chapters, not only those in the language i want...
Is it possible to filter the select_related so that in my template, in {{book.translations}} i only have the translation in the language i asked for (same for chapters)?
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.