将视图中的Django Queryset传递给模板 [英] Passing Django Queryset in Views to Template

查看:71
本文介绍了将视图中的Django Queryset传递给模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django Views,它具有将正确的类别传递给模板的逻辑。

I have a Django Views which has some logic for passing the correct category to the template.

class ProductListView(ListView):
    model = models.Product
    template_name = "catalogue/catalogue.html"

    def get_queryset(self):
        category = self.kwargs.get("category")
        if category:
            queryset = Product.objects.filter(category__iexact=category)
        else:
            queryset = Product.objects.all()
        return queryset

我不知道如何将其传递给模板,我的模板代码如下:

I can't work out how to pass this to the template, my template code is as below:

            {% for product in products %}
            <tr>   
                <td><h5>{{ product.name }}</h5>
                <p>Cooked with chicken and mutton cumin spices</p></td>
                <td><p><strong>£ {{ product.price }}</strong></p></td>
                <td class="options"><a href="#0"><i class="icon_plus_alt2"></i></a></td>
            </tr>
            {% endfor %}  

我很确定我的模板语法是错误的,但是如何如何将特定类别传递给模板?因此,如果我有一个名为 Mains的类别,该如何将Mains的所有产品传递给模板。

I am pretty sure my template syntax is wrong, but how do I pass the particular category to the template? So if I have a category called 'Mains' how do I pass all the products for mains to the template.

推荐答案

添加以下方法

def get_context_data(self, **kwargs):
    context = super(ProductListView, self).get_context_data(**kwargs)
    some_data = Product.objects.all()
    context.update({'some_data': some_data})
    return context

现在,在模板中,您可以访问 some_data 变量。您还可以根据需要添加任意数量的数据来更新上下文字典。

So now, in your template, you have access to some_data variable. You can also add as many data updating the context dictionary as you want.

如果您仍然想使用 get_queryset 方法,那么您可以使用 object_list

If you still want to use the get_queryset method, then you can access that queryset in the template as object_list

{% for product in object_list %}
...
{% endfor %}

这篇关于将视图中的Django Queryset传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆