带有for循环的Django queryset并传递给模板

时间:2018-03-31 18:06:37

标签: python django templates dictionary

我正在尝试使用多重搜索。例如,我将搜索“Feas.Meat”。我的搜索结果将返回鱼和肉产品。我正在使用拆分功能拆分搜索输入。并使用Django Filter获取搜索查询。但Filter返回查询集。我无法弄清楚如何使用循环以格式化方式(如Array List)发送特定文本的查询集列表。我想要的东西像: ['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 %}

1 个答案:

答案 0 :(得分:0)

试试这个:

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']。