gpt4 book ai didi

python - Django 如何从单个 View 到单个模板获取多个查询集的多个 context_object_name

转载 作者:太空宇宙 更新时间:2023-11-03 13:11:04 27 4
gpt4 key购买 nike

我想从单个 View 运行多个 查询集。我已经完成了将单个 get_queryset 和单个 context_object_name 传递到 index.html 模板中的操作:

class IndexView(generic.ListView):
template_name = 'doorstep/index.html'
context_object_name = 'all_hotels'

def get_queryset(self):
return Hotel.objects.all().order_by('rating').reverse()[:3]

现在,我需要运行这个查询集Hotel.objects.all().order_by('star').reverse()[:3]从相同的 IndexView 并将此查询集中的 context_object_name 传递给相同的 template_name

我在模板中得到的值是 {% for hotel in all_hotels %}

最佳答案

覆盖 get_context_data并将任何其他查询集添加到上下文中。

class IndexView(generic.ListView):
template_name = 'doorstep/index.html'
context_object_name = 'all_hotels'

def get_queryset(self):
return Hotel.objects.all().order_by('rating').reverse()[:3]

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['star_hotels'] = Hotel.objects.all().order_by('star').reverse()[:3]
# Add any other variables to the context here
...
return context

您现在可以在模板中访问 {{ star_hotels }}

关于python - Django 如何从单个 View 到单个模板获取多个查询集的多个 context_object_name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43387875/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com