【问题标题】:Django queryset with for loop and pass to template带有for循环的Django查询集并传递给模板
【发布时间】:2018-09-10 11:08:42
【问题描述】:

我正在尝试使用多重搜索。例如,我将搜索“Feas.Meat”。我的搜索结果将返回我的鱼和肉产品。我正在使用拆分功能拆分搜索输入。并使用 Django Filter 来获取搜索查询。但过滤器返回查询集。我不知道如何使用循环以格式化方式(如数组列表)发送特定文本的查询集列表。我想要类似的东西: ['Fish':'Fish Queryset','Meat':'Meat Querysset']。我明确地为 2/3 输入逐个发送变量。我想像数组列表一样发送到模板。 我的视图功能:

#Split Definitions change only  here

search_input = search_text.split('.')
len_search_items = len(search_input)

#Create search query for appropriated searched products

if(len_search_items==1):
        search_split = search_input[0]
        #Store the split search text in Array

        searched_products=list(Item.objects.filter(title__contains=search_split))
        args = { 'len_search_items':len_search_items,'search_split':search_split,'form':form, 'search_input':search_input,'searched_products':searched_products,'search_text':search_text}

模板代码:

{% extends 'base.html' %}
{% block search_content %}

<h2>Search Page</h2>

{% include "snippets/search-form.html" %}

<h2> String Separatin={{ search_input }}</h2>
<h2> Searched For={{ search_text }}</h2>

<h2>  Searched For ={{ len_search_items }} products</h2>
<h2>  Search Found Result  ={{ searched_products_len }} products</h2> 
<h2> Searched For ={{ search_split }}</h2>

{% if searched_products %}
<ul>

    <h2>Searched Product List</h2>
    {% for item in searched_products %}


    <li> <a href="{% url 'detail' item.id %}">{{ item.title }}</a></li>

    {% endfor %}
</ul>

{% else %}


<h2>No Search Matched</h2>

{% endif %} 


{% if searched_products1 %}
<ul>
    <h2> Searched For ={{ search_split1 }}</h2>
    <h2>Searched Product List</h2>
    {% for item in searched_products1 %}


    <li> <a href="{% url 'detail' item.id %}">{{ item.title }}</a></li>

    {% endfor %}
</ul>

{% else %}


<h2>No Search Matched</h2>

{% endif %}

{% if searched_products2 %}
<ul>
    <h2> Searched For ={{ search_split2 }}</h2>
    <h2>Searched Product List</h2>
    {% for item in searched_products2 %}


    <li> <a href="{% url 'detail' item.id %}">{{ item.title }}</a></li>

    {% endfor %}
</ul>

{% else %}


<h2>No Search Matched</h2>

{% endif %}
{% endblock %}

【问题讨论】:

  • 请正确添加您的预期输出。
  • 是的。但是如何使用循环来做到这一点。当我正在搜索多个项目时

标签: python django templates dictionary


【解决方案1】:

试试这个:

search_products = {search_split: Item.objects.filter(title__contains=search_split)}

而不是这个:

searched_products=list(Item.objects.filter(title__contains=search_split))

如果有人搜索肉类,你会得到类似:

{'meat': [{'name': 'meat1'}, {'name': 'meat2'}]}

我希望我明白你想要什么

我想要类似的东西:['Fish': 'Fish Queryset', 'Meat': 'Meat Querysset']。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 2023-04-09
    • 2014-02-14
    • 2021-09-05
    • 1970-01-01
    • 2014-11-04
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多