我在DB钱包(id,name)和余额(id,wallet_id)中有两个表
我需要由两个牢房组成的桌子(后,日期)
第一格的钱包在哪里,第二格的钱包在哪里平衡?
{% for wallets1 in wallets %}
<tr>
{% for balance1 in balance %}
{% if balance1.wallet_id == wallets1.id %}
<td> {{ balance1.balance }}</td>
{% endif %} {% endfor %}
{% endfor %}如果我们有硬币的余额,如果balance1.wallet_id需要打印"0“,我们就打印余额。
接下来的困难。如果我那样做
{% for wallets1 in wallets %}
<tr>
{% for balance1 in balance %}
{% if balance1.wallet_id == wallets1.id %}
<td> {{ balance1.balance }}</td>
{% else %}
<td> 0</td>
{% endif %} {% endfor %}
{% endfor %}零会被打印很多次
视图
wallets = Wallet.objects.all()
balance = User_balance.objects.filter(user_id= user.id)
args['wallets'] = wallets
args['balance'] = balance
return render_to_response("coins.html", args, user.id)模型
class Wallet(models.Model):
name = models.CharField(max_length=100)
class User_balance(models.Model):
user_id = models.IntegerField()
wallet_id = models.IntegerField()
balance = models.CharField(max_length=100)发布于 2018-07-03 07:11:02
您必须在您的视图中这样注释平衡。
wallers = Wallet.objects.all().annotate(total_balance=models.Count('balance'))
...
return render(request, 'template.html', {"wallets": wallets})然后在你的html打印钱包像这样
<table>
<tr><th>wallet</th><th>balance</th></tr>
{% for wallet in wallets %}
<tr>
<td>{{ wallet.name }}</td>
<td>{{ wallet.total_balance|default:0 }}</td>
</tr>
{% endfor %}
</table>发布于 2018-07-03 06:56:42
你没有发布你的观点或模型,所以我们必须假设一些事情,但基本上你做错了。因为余额在钱包上有一个外键,所以您不必遍历每个钱包的所有余额,您可以只使用使用反向关系
{% for wallet in wallets %}
<tr>
{% for balance in wallet.balance_set.all %}
<td> {{ balance.balance }}</td>
{% else %}
<td> 0</td>
{% endfor %}
</tr>
{% endfor %}https://stackoverflow.com/questions/51148142
复制相似问题