如何在 html 中呈现来自 groupby 查询的结果 - Django
How to render results from groupby query in html - Django
我正在尝试通过从视图到 HTML table 的查询来呈现组的结果,但它没有返回任何内容。我本来可以成功列出所有结果,但在应用总和聚合后我无法让它出现。
Django 视图 - 分组依据
def get_asset_price(request):
# CryptoAssets is the model
obj = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol')
obj = obj.annotate(total_units=Sum('units'),
total_cost=Sum('cost'))\
.order_by('symbol')
# Returns list of dictionaries
context = {
'object': obj
}
return render(request, 'coinprices/my-dashboard.html', context)
HTML
<style>
table, th, td {
border: 1px solid black;
}
</style>
<div class="container">
<h1>My Dashboard</h1>
<table>
<tr>
<th>Symbol</th>
<th>Total Units</th>
<th>Total Cost</th>
</tr>
{% for row in object %}
<tr>
<td>{{ row.symbol }}</td>
<td>{{ row.units }}</td>
<td>{{ row.cost }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
我将在下面提供没有分组依据的视图。
Django 视图 - 没有分组依据
def get_asset_price(request):
# CryptoAssets is the model
obj = CryptoAssets.objects.all().filter(user_id=request.user.id)
# Returns list of objects
context = {
'object': obj
}
return render(request, 'coinprices/my-dashboard.html', context)
我认为您正在调用您的对象上不存在的属性。您的对象的类型是字典列表。将您的模板代码更改为如下内容(这是最简单的方法,也许您可以稍后改进它,例如添加类似于 this question 中使用的模板标签):
<table>
<tr>
<th>Symbol</th>
<th>Total Units</th>
<th>Total Cost</th>
</tr>
{% for row in object %}
<tr>
{% for key, value in row.items %}
<td>{{ key }}</td>
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
我正在尝试通过从视图到 HTML table 的查询来呈现组的结果,但它没有返回任何内容。我本来可以成功列出所有结果,但在应用总和聚合后我无法让它出现。
Django 视图 - 分组依据
def get_asset_price(request):
# CryptoAssets is the model
obj = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol')
obj = obj.annotate(total_units=Sum('units'),
total_cost=Sum('cost'))\
.order_by('symbol')
# Returns list of dictionaries
context = {
'object': obj
}
return render(request, 'coinprices/my-dashboard.html', context)
HTML
<style>
table, th, td {
border: 1px solid black;
}
</style>
<div class="container">
<h1>My Dashboard</h1>
<table>
<tr>
<th>Symbol</th>
<th>Total Units</th>
<th>Total Cost</th>
</tr>
{% for row in object %}
<tr>
<td>{{ row.symbol }}</td>
<td>{{ row.units }}</td>
<td>{{ row.cost }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
我将在下面提供没有分组依据的视图。
Django 视图 - 没有分组依据
def get_asset_price(request):
# CryptoAssets is the model
obj = CryptoAssets.objects.all().filter(user_id=request.user.id)
# Returns list of objects
context = {
'object': obj
}
return render(request, 'coinprices/my-dashboard.html', context)
我认为您正在调用您的对象上不存在的属性。您的对象的类型是字典列表。将您的模板代码更改为如下内容(这是最简单的方法,也许您可以稍后改进它,例如添加类似于 this question 中使用的模板标签):
<table>
<tr>
<th>Symbol</th>
<th>Total Units</th>
<th>Total Cost</th>
</tr>
{% for row in object %}
<tr>
{% for key, value in row.items %}
<td>{{ key }}</td>
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>