Complex SQL query on class-based generic view

Hi all, I’m pulling my hair out to figure out how I can make this query within a class-based generic view.

´´´select b.book_name, s.title,
from books_books b, books_sessoes s
where = 3 AND b.sessaoid_id =´´´

If I run this query I get:
Screenshot 2022-12-14 at 14.18.07

The where should be the book id variable from the context within the view, here is the view:

´´´class DetalhesLivro(DetailView):
model = Books
template_name = ‘books/detalhe_livro.html’

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context ['sessao'] = Sessoes.objects.values('title')
    return context´´´

this is the template that calls the template “books/detalhe_livro.html”

´´´{% for livros in sessoes.books_set.all %}

<img align=“center” widht=“128” height=“200” src= {{ livros.image.url }}/>
{{ livros.book_name }}

{% endfor %}´´´

the url file:

´´´app_name = ‘book’
urlpatterns = [
path(‘’, views.IndexView.as_view(), name=‘index’),
path(‘about/’, views.about, name=‘Books-About’),
int:pk/’, views.DetailView.as_view(), name=‘detalhe’),
path(‘detalhe_livro/int:pk/’, views.DetalhesLivro.as_view(), name=‘detalhe_livro’),

and this is the model:

´´´class Sessoes(models.Model):
title = models.CharField(max_length=100)
sessao_date = models.DateField()
def str(self):
return self.title

class Books(models.Model):
sessaoid = models.ForeignKey(Sessoes, on_delete=models.CASCADE)
book_name = models.CharField(max_length=100)
description = models.CharField(max_length=250)
sinopse = models.TextField()
image = models.ImageField(upload_to=‘books/’)´´´

the result I get is all the values in the Seesao table and I only want the tittle for the specific Sessao of that Book

Any help would be much appreciated.

could this be what you’re after?

    book = Book.objects.select_related(
except Book.DoesNotExist:
    print('no book found :[')


A few comments though:

  1. exposing a primary key is generally not too good (unless the app is internal, etc)?
  2. your DetailView has an object property. Learn how to use it.
  3. 1+2 = use a slug field? (even if you have to concatenate it with something else, such as a uuid?)
  4. check this incredible tool:

As a side note, you need to surround your code with backtick - ` characters, not apostrophe - ' or any other kind of “smart quote” character.

Also, the line of ``` must be lines by themselves, not as the beginning of a line of code.

Thanks plopidou, that worked just fine.

Hello Ken, thanks for letting me know.