可以发送2个查询集来响应吗?

时间:2010-08-07 08:37:48

标签: django django-templates

render_to_response是否可以传递多于一个变量的变量?例如,在我的应用程序中,我有一个成员模型,然后我想显示成员信息和出勤信息。我是否必须将参数作为元组提供? 在此先感谢,
迪恩

2 个答案:

答案 0 :(得分:4)

Render_to_response接受用于渲染的上下文。据我所知,您可以在上下文中传递的变量数量没有限制。这包括QuerySet。例如:

def my_view(request, *args, **kwargs):
    # ... etc ...
    q1 = Model1.objects.filter(**conditions)
    q2 = Model2.objects.filter(**conditions)
    context = dict(q1 = q1, q2 = q2)
    return render_to_response('my_template.html', context_instance = RequestContext(request, context))

我的示例使用RequestContext,但没有它也应该没问题。

# Template
{% for foo in q1 %} {{ foo }} {% endfor %}
... stuff ...
{% for bar in q2 %} {{ bar }} {% endfor %}

答案 1 :(得分:3)

虽然Manoj是正确的,您可以通过构建自己的上下文实例并将其作为关键字参数传递给render_to_response来传递变量,但使用第二个位置参数render_to_response通常更短/更简单,它接受添加到幕后的背景。

快速浏览the docs for render_to_response。它们的示例用法如下所示(并允许您将可以存储在dict中的任何内容传递给渲染器):

from django.shortcuts import render_to_response

def my_view(request):
    # View code here...
    return render_to_response('myapp/index.html', {"foo": "bar"},
        mimetype="application/xhtml+xml")
相关问题