简体   繁体   中英

How can perform two related database query in get_context_data i.e. use “request”?

I need to perform two database queries ie

select * from books

and

select * from chapters where book_id=id

On the UI i need to have a list of books (that i can get with the first query) and on click of any of the book, i want to use its id to get all the chapters(from 2nd query). I am trying to create a class based view(template view) and having issues in how to perform these two queries in get_context_data() . I tried using request.GET.get but failed. can anyone please help.

i want to have UI for eg.

Book 1
   chapter 1
   chapter 2
Book 2 
Book 3

There are multiple ways, the easiest one is:

https://docs.djangoproject.com/en/1.8/topics/class-based-views/generic-display/#adding-extra-context

Assuming some Model/View names:

models.py

class Book(model.Model):
    title = CharField()

class Chapter(model.Model):
    book = ForeignKey(Book, related_name='chapters')

views.py

class BookDetailView(DetailView):
    model = Book

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(BookDetailView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['all_books'] = Book.objects.all()
        return context

bookdetails.html

{{ object.title }}
{% for chapter in object.chapters %}
    {{ chapter.title }}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM