繁体   English   中英

Django如何从单个视图到单个模板获取多个查询集的多个context_object_name

[英]Django how to get multiple context_object_name for multiple queryset from single view to single template

我想从单个视图运行多个 queryset。 我已经完成了单个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]

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

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

覆盖get_context_data并将任何其他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 }}了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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