我有大约1000记录的数据值,我想根据类别在同一模板文件中显示该数据的子集。我在寻找真正可行的解决方案时遇到了麻烦。下面是我的目的,但我很确定有一种更有效的方法来实现此目的。
查看
def man_org_list(request):
manufacturers = Organization.objects.filter(member__member_flag=1, member__member_type='Manufacturer').order_by('id')
suppliers = Organization.objects.filter(member__member_flag=1, member__member_type='Supplier').order_by('id')
distributor = Organization.objects.filter(member__member_flag=1, member__member_type='distributor').order_by('id')
return render(request, 'profiles/man_dash.html', {'man': manufacturers, 'sup': suppliers, 'dist': distributor})
urls.py
urlpatterns = [
url(r'^$', views.org_list, name='org_list'),
url(r'^(?P<id>\d+)/$', views.org_details, name='org_details'),
url(r'^man_dash/', views.man_org_list, name='man_org_list')
]
我要根据类别更改的部分代码:
{% if request.get_full_path == '/profiles/man_dash/manufacturers/' %}
{% for org in man %}
<tr>
<th scope="row">{{ org.id }}</th>
<td>{{ org.org_name }}</td>
<td>{{ org.org_type }}</td>
{% for member in org.member.all %}
<td>{{ member.member_flag }}</td>
{% endfor %}
{% for c_score in org.c_score.all %}
<td>{{ c_score.completeness_score }}%</td>
{% endfor %}
<td><a href="{% url 'org_details' org.id %}" target="_blank">View</a></td>
</tr>
{% endfor %}
{% endif %}
您可以在代码段中看到,我正在使用request.get_full_path来匹配URL路径以显示数据。但是,使用这种方法,我将不得不复制同一代码块3次而只更改一页,这使我相信这不是实现此目的的理想方法。
是否有更好的方法可以通过视图或url.py?
答案 0 :(得分:0)
我;我不确定那是否是您所需要的,但请尝试。
首先,您的网址似乎无法正确匹配:
让我们添加将从网址中捕获的member_type
参数
urlpatterns = [
url(r'^$', views.org_list, name='org_list'),
url(r'^(?P\d+)/$', views.org_details, name='org_details'),
url(r'^man_dash/<str:member_type>/', views.man_org_list, name='man_org_list')
]
现在将kwarg添加到视图中:
def man_org_list(request, member_type=None):
member_type_map = {
'manufacturers': 'Manufacturer',
'suppliers': 'Supplier',
'distributors': 'distributor'
}
member_type = member_type_map.get(member_type, None)
if member_type is None:
raise Http404
queryset = Organization.objects.filter(member__member_flag=1, member__member_type=member_type).order_by('id')
return render(request, 'profiles/man_dash.html', {'object_list': queryset})
现在您的模板仅需要遍历对象列表
{% for org in object_list %}
<tr>
<th scope="row">{{ org.id }}</th>
<td>{{ org.org_name }}</td>
<td>{{ org.org_type }}</td>
{% for member in org.member.all %}
<td>{{ member.member_flag }}</td>
{% endfor %}
{% for c_score in org.c_score.all %}
<td>{{ c_score.completeness_score }}%</td>
{% endfor %}
<td><a href="{% url 'org_details' org.id %}" target="_blank">View</a></td>
</tr>
{% endfor %}