如何返回查询集和字典

时间:2019-04-30 23:21:43

标签: django

我正在尝试传递一个查询集和一个字典,上下文是查询集,对于本示例来说,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,
    })

2 个答案:

答案 0 :(得分:1)

根据您的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)

     

您可以看到,第三个参数是 context (包含在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)

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

例如

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

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

答案 1 :(得分:0)

您是否添加: {'container':container, 'container_contents': container_contents, 'unassigned_samples': unassigned_samples, }

到上下文词典?上下文字典中可以包含很多对象。