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,
})
解决方案
根据您的 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 %}
推荐阅读
- mysql - 如何根据条件中的值仅显示行?
- angularjs - AngularJS:清除某些元素上的验证错误
- c# - C#:起订量:消息:System.NotSupportedException:不支持的表达式:item => item.RouteId 不可覆盖的成员
- node.js - 在大数据中替换字符串数组中的子字符串 mongodb V4.2
- python - 超过 1 次分配后创建了多少个对象?
- docker - 将 container_cpu_load_average_10s 设为零
- uefi - UEFI 变量命名空间“{8be4df61-93ca-11d2-aa0d-00e098032b8c}”是否有标准名称?
- c++ - 从 double 到 int 的类型转换。没见过这种区别
- oracle-cloud-infrastructure - 使用 OCI CLI 从 OCI 实例获取公共 IP
- python - NameError:名称“bitearray”未定义