首页 > 解决方案 > 如何返回查询集和字典

问题描述

我正在尝试传递一个查询集和一个字典,上下文是查询集,对于这个示例 unassigned_samples2 是字典,在我的模板中,我可以获取要显示的字典或查询集,但不能同时包含两者,这取决于我是否包含上下文查询集。任何想法如何让这个工作?

def detailcontainer(request, container_id):
    container = get_object_or_404(Container, pk=container_id)
    samples = container.samples.all()
    container_contents = container.samples.all()
    unassigned_samples = Sample.objects.all()[:10]
    unassigned_samples2 = Sample.objects.all()

    qs = Sample.objects.all()
    easting_query = request.GET.get('area_easting')
    northing_query = request.GET.get('area_northing')
    context_query = request.GET.get('context_number')
    sample_number_query = request.GET.get('sample_number')
    sample_type_query = request.GET.get('sample_type')

    if easting_query != '' and easting_query is not None:
        qs = qs.filter(area_easting__icontains=easting_query)
    if northing_query != '' and northing_query is not None:
        qs = qs.filter(area_northing__icontains=northing_query)
    if context_query != '' and context_query is not None:
        qs = qs.filter(context_number__icontains=context_query)
    if sample_number_query != '' and sample_number_query is not None:
        qs = qs.filter(sample_number__icontains=sample_number_query)
    if sample_type_query != '' and sample_type_query is not None:
        qs = qs.filter(sample_type__icontains=sample_type_query)

    qs = qs

    context = {
        'queryset': qs
    }
    return render(request, 'container/detailcontainer.html', context,
    {'container':container,
    'container_contents': container_contents,
    'unassigned_samples': unassigned_samples,
    })

标签: django

解决方案


根据您的 django 版本,您可以查看https://docs.djangoproject.com/en/2.2/topics/http/shortcuts/(从页面右下角选择特定版本)以获取render()函数的签名。

render()函数的签名是render(request, template_name, context=None, content_type=None, status=None, using=None).

您可以看到,第三个参数是上下文(包含在 django 模板中用作模板上下文变量的键的字典)。

只是改变

context = {
    'queryset': qs
}

return render(request, 'container/detailcontainer.html', context,
{'container':container,
'container_contents': container_contents,
'unassigned_samples': unassigned_samples,
})

context = {
    'queryset': qs
    'container': container,
    'container_contents': container_contents,
    'unassigned_samples': unassigned_samples
}

return render(request, 'container/detailcontainer.html', context)

最后,在您的模板中,您可以访问所有已定义的模板上下文变量queryset,例如container等。

例如

  • {% for sample in queryset %} {{sample.pk}} {% endfor %}

  • {% for item in unassigned_samples %} {{item.pk}} {% endfor %}


推荐阅读