我有一个简单的Django模型和Q查找,一切都按预期工作,但我希望过滤结果显示在单独的DIV中,同时保持原始查询列表未经过滤,如附加图像中的注释。下面是我的代码,带注释的屏幕截图以及dev服务器上页面的链接。任何指示都会很棒。谢谢。
查看
def plaque_list(request):
today = timezone.now().date()
queryset_list = Plaque.objects.active().order_by("first_name")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Plaque.objects.all().order_by("first_name")
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(first_name__contains=query) |
Q(last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"queryset_list": queryset_list,
"title": "Locate a Veteran",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "plaques/plaque_list.html", context)
模板
...
{% for obj in object_list %}
<tr>
<th><a href="{{ obj.get_absolute_url }}">{{ obj.first_name }}</a></th>
<th><a href="{{ obj.get_absolute_url }}">{{ obj.last_name }}</a></th>
<th>{{ obj.branch }}</th>
<th>{{ obj.rank }}</th>
<th>{{ obj.wall|upper }}</th>
<th>{{ obj.direction|title }}</th>
<th>{{ obj.row }}</th>
<th>{{ obj.plaque_num }}</th>
</tr>
...
{% endfor %}
答案 0 :(得分:1)
按照devxplorer的建议,只需在您的上下文字典中添加第二个查询集,然后使用它来呈现您的特殊div
。
def plaque_list(request):
today = timezone.now().date()
queryset_list = Plaque.objects.active().order_by("first_name")
if request.user.is_staff or request.user.is_superuser:
queryset_list = Plaque.objects.all().order_by("first_name")
query = request.GET.get("q")
filtered_results = None
if query:
filtered_results = queryset_list.filter(
Q(first_name__contains=query) |
Q(last_name__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 8) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"queryset_list": queryset_list,
'filtered_results': filtered_results,
"title": "Locate a Veteran",
"page_request_var": page_request_var,
"today": today,
}
return render(request, "plaques/plaque_list.html", context)
然后你可以在那个特殊的div中循环filtered_results
。