【发布时间】:2018-10-23 23:59:47
【问题描述】:
我正在尝试在 Django 中创建一个查询,该查询调用满足过滤器某些条件(使用 filter)的唯一行(使用 distinct)
这里是使用的文件:
views.py
def cat_details(request, pk):
current_user = request.user
selected_cat = get_object_or_404(Category, pk=pk)
selected_items = ItemIn.objects.all().filter(item_category=selected_cat).values_list('item_name', flat=True).distinct()
all_cats = Category.objects.all()
cat_count = all_cats.count()
item_count = ItemIn.objects.values_list('item_name', flat=True).distinct().count() # returns a list of tuples..
#all_units = Item.objects.aggregate(Sum('item_quantity'))['item_quantity__sum']
context = {
#'all_units': all_units,
'item_count': item_count,
'cat_count': cat_count,
'selected_items': selected_items,
'selected_cat': selected_cat,
'current_user': current_user,
}
return render(request, 'townoftech_warehouse/cat_details.html', context)
名为selected_items 的变量是问题所在!
这就是我如何使用这个视图函数
HTML
{% extends 'townoftech_warehouse/base.html' %}
{% block content %}
{% load static %}
<div class="card">
<div class="card-header">
الاصناف فى المخزن
</div>
<div class="card-body">
<h3 align="right"> {{ selected_cat }}</h3>
<footer><a href="{% url 'edit_cat' selected_cat.pk%}"><button type="button" class="btn btn-dark">تعديل إسم الفئة</button></a>
<a href="{% url 'category_delete' selected_cat.pk%}"><button type="button" class="btn btn-dark">مسح الفئة</button></a>
</footer>
</div>
</div>
<div style="overflow: auto;height: 280px">
<table class="table table-bordered">
<tbody>
{% for item in selected_items %}
<tr align="right">
<th scope="row"><a href = "{% url 'items' item.pk%}">{{ item.item_name }}</a></th>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<br>
<br>
<div align="right"><a href="{% url 'cat' %}"><button type="button" class="btn btn-danger">رجوع</button></a></div>
{% endblock %}
每当我尝试打开此页面时,我得到的错误是:
错误
NoReverseMatch at /category/15/
Reverse for 'items' with arguments '('',)' not found. 1 pattern(s) tried: ['item\\/(?P<pk>[0-9]+)\\/$']
更新
我已经从 HTML 文件中删除了链接
变了
{% for item in selected_items %} {{ item.item_name }} {% endfor %}
变得像
{% for item in selected_items %}
<tr align="right">
<th scope="row">{{ item.item_name }}</th>
</tr>
{% endfor %}
错误消失了,但它现在给了我一个空值列表!
【问题讨论】: