我有这样的代码,我希望它能够返回多个产品。现在它只返回最后一个。我认为这是因为变量被覆盖了,但我不知道其他方法来修复它
def result(request):
rawquery = request.GET.get('q') #gets the product name to search from a form
Product_set = Product.objects.filter(name__icontains=rawquery).distinct()
for product in Product_set:
name = product.name
id = product.id
store_name = product.store_name
Price_set = Scan.objects.filter(product=id)
for price in Price_set:
current_price = price.price
context = {
'name': name,
'store_name': store_name,
'price': current_price,
'query': rawquery
}
return render(request, 'result.html', context)
这是模板
% {extends 'base.html' %}
{% block content %}
<h1>Results for {{ query }} </h1>
<p> {% if name %} {{name}} {% else %} None {% endif %} | {% if store_name %} {{store_name}} {% endif %} | {% if price %} {{price}} {% endif %} </p>
{% endblock content %}
您必须将产品附加到列表中:
def result(request):
rawquery = request.GET.get('q') #gets the product name to search from a form
Product_set = Product.objects.filter(name__icontains=rawquery).distinct()
products = []
for product in Product_set:
price = Scan.objects.filter(product=product.id).first()
products.append({
'name': product.name,
'store_name': product.store_name,
'price': price.price
})
return render(request, 'result.html', {'query': rawquery, 'products': products})
你现在可以在这里循环产品:
{% extends 'base.html' %}
{% block content %}
<h1>Results for {{ query }} </h1>
{% for product in products %}
<p> {{product.name}} | {{product.store_name}} | {{product.price}} </p>
{% endfor %}
{% endblock %}