简体   繁体   中英

A little confused about Django generic views

my question could be very basic and I apologize for posting such questions here. Unfortunately, I couldn't find a proper solution for this. I've got two classes, one of them inherits from generic.DetailView and the other one inherits from generic.ListView. Besides getting details of the Post model, I would like to call a query in the same template to pull out posts that are marked as essential. Though, I'm a little confused about the correct way of doing it. I would be thankful if anyone guides me about this.

from django.shortcuts import render
from django.views import generic
from .models import Post


class Details(generic.DetailView):
    model = Post

class EssentialPosts(generic.ListView):
    def getessentialposts(self):
        queryset = Post.objects.filter(essential=True).order_by('-created_on')
        return queryset


class PostDetail(Details , EssentialPosts):
    template_name = 'post-detail.html'

You can do as following:

class PostDetailView(DetailView):
     model = Post

     def get_context_data(self, **kwargs):
         context = super().get_context_data(**kwargs)
         context['essential_posts'] = Post.objects.filter(essential=True).order_by('-created_on')
         return context

I think perhaps the easiest solution for this would simply be a generic view where you perform logic and return a custom context dictionary.

The other options would perhaps be modifying get_context_data to get what you want, or perhaps performing some extra actions within the view, as seen in the documentation here: https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/ .

from django.shortcuts import render
from django.views import View


class MyGenericVIew(View):
    initial = {'key': 'value'}
    template_name = 'my_template.html'

    def get(self, request, *args, **kwargs):
        all_posts = Post.objects.all()
        essential_posts = Post.objects.filter(essential=True)
        return render(request, 
                      self.template_name, 
                      {'essential_posts': essential_posts,
                       'all_posts': all_posts})

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