【发布时间】:2019-03-01 04:36:16
【问题描述】:
我正在尝试使用 Django 模板从 MySQL 数据库中加载对象列表。我可以使用Product.objects.values() 从数据库中加载对象并将其转换为字典,然后将该字典作为上下文传递给渲染函数。但是当我加载我的页面时,它不会迭代字典。有人有什么想法吗?
def product(request):
print(Product.objects.values())
d = Product.objects.values()
newdict = {}
for entry in d:
name = entry.pop('name') # remove and return the name field to use as a key
newdict[name] = entry
print(newdict)
return render(request, 'product.html', newdict)
<div class="col-12 col-lg-6 add_to_cart_block">
{% for item in newdict.items %}
{{newdict|length}}
<div class="card bg-light mb-3">
<div class="card-body">
<p class="price">{{item}}</p>
<p class="price_discounted">149.90 $</p>
<form method="get" action="cart.html">
<div class="form-group">
<label for="colors">Color</label>
<select class="custom-select" id="colors">
<option selected>Select</option>
<option value="1">Blue</option>
<option value="2">Red</option>
<option value="3">Green</option>
</select>
</div>
<div class="form-group">
<label>Quantity :</label>
<div class="input-group mb-3">
<div class="input-group-prepend">
<button type="button" class="quantity-left-minus btn btn-danger btn-number" data-type="minus" data-field="">
<i class="fa fa-minus"></i>
</button>
</div>
<input type="text" class="form-control" id="quantity" name="quantity" min="1" max="100" value="1">
<div class="input-group-append">
<button type="button" class="quantity-right-plus btn btn-success btn-number" data-type="plus" data-field="">
<i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
<a href="cart.html" class="btn btn-success btn-lg btn-block text-uppercase">
<i class="fa fa-shopping-cart"></i> Add To Cart
</a>
</form>
<div class="product_rassurance">
<ul class="list-inline">
<li class="list-inline-item"><i class="fa fa-truck fa-2x"></i><br/>Fast delivery</li>
<li class="list-inline-item"><i class="fa fa-credit-card fa-2x"></i><br/>Secure payment</li>
<li class="list-inline-item"><i class="fa fa-phone fa-2x"></i><br/>+33 1 22 54 65 60</li>
</ul>
</div>
<div class="reviews_product p-3 mb-2 ">
3 reviews
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
<i class="fa fa-star"></i>
(4/5)
<a class="pull-right" href="#reviews">View all reviews</a>
</div>
<div class="datasheet p-3 mb-2 bg-info text-white">
<a href="" class="text-white"><i class="fa fa-file-text"></i> Download DataSheet</a>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
【问题讨论】:
-
我看不出有什么好的理由使用
.values()和字典修改而不仅仅是.all()。 -
当我使用 .all() 它传递了一个查询集。我需要将其转换为字典,以便使用模板对其进行迭代。
-
你知道如何将 .all() 转换为 dict 吗?
-
您确实不需要需要将查询集转换为字典。
标签: python mysql django django-templates