![](/img/trans.png)
[英]A little confused about rebuild/update_index for Django-Haystack
[英]A little confused about Django generic views
我的問題可能非常基本,我很抱歉在這里發布這些問題。 不幸的是,我找不到合適的解決方案。 我有兩個類,其中一個繼承自 generic.DetailView,另一個繼承自 generic.ListView。 除了獲取 Post 模型的詳細信息之外,我還想在同一模板中調用一個查詢來提取標記為必不可少的帖子。 雖然,我對正確的做法有點困惑。 如果有人指導我,我將不勝感激。
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'
您可以執行以下操作:
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
我認為最簡單的解決方案可能只是一個通用視圖,您可以在其中執行邏輯並返回自定義上下文字典。
其他選項可能是修改get_context_data
以獲得您想要的內容,或者可能在視圖中執行一些額外的操作,如此處的文檔所示: https : //docs.djangoproject.com/en/3.0/topics/class-based -視圖/通用顯示/ 。
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})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.