无法在页面中输出数据

时间:2018-07-03 06:45:18

标签: python django

我在数据库钱包(id,name)和余额(id,wallet_id)中有2个表

我需要由2个单元格组成的表格(发布,日期)

第一个单元格中的所有钱包在哪里,第二个中的余额在哪里

{% 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)

2 个答案:

答案 0 :(得分:2)

您没有发布视图或模型,因此我们不得不假设一些事情,但是基本上您做错了。由于余额在钱包中具有外键,因此您不必遍历每个钱包的所有余额,只需use the reverse relationship

{% for wallet in wallets %}
<tr>
  {% for balance in wallet.balance_set.all  %} 
    <td> {{ balance.balance }}</td>
  {% else %}
    <td> 0</td>
  {% endfor %}
</tr>
{% endfor %}

答案 1 :(得分:0)

您必须像这样在视图中注释余额

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>
相关问题