我有一个Modelformset:
TransactionFormSet = modelformset_factory(Transaction, exclude=("",))
使用此模型:
class Transaction(models.Model):
account = models.ForeignKey(Account)
date = models.DateField()
payee = models.CharField(max_length = 100)
categories = models.ManyToManyField(Category)
comment = models.CharField(max_length = 1000)
outflow = models.DecimalField(max_digits=10, decimal_places=3)
inflow = models.DecimalField(max_digits=10, decimal_places=3)
cleared = models.BooleanField()
这是模板:
{% for transaction in transactions %}
<ul>
{% for field in transaction %}
{% ifnotequal field.label 'Id' %}
{% ifnotequal field.value None %}
{% ifequal field.label 'Categories' %}
// what do i do here?
{% endifequal %}
<li>{{ field.label}}: {{ field.value }}</li>
{% endifnotequal %}
{% endifnotequal %}
{% endfor %}
</ul>
{% endfor %}
视图:
def transactions_on_account_view(request, account_id):
if request.method == "GET":
transactions = TransactionFormSet(queryset=Transaction.objects.for_account(account_id))
context = {"transactions":transactions}
return render(request, "transactions/transactions_for_account.html", context)
我想在页面上列出所有交易信息。如何列出交易的"帐户"属性和"类别"?当前,模板仅显示其ID,我想为用户获得一个不错的表示(优先摘自他们的 str ()方法)。
我看到的唯一方法是在表单集上迭代,获取帐户和类别对象的ID,通过其ID获取对象并将我想要的信息存储在列表中,然后将其从那里拉出在模板中,但这对我来说似乎很恐怖。
有更好的方法吗?
多亏了评论,我发现我在做的事情很愚蠢,毫无意义。
这有效:
1)获取所有交易对象
transactions = Transaction.objects.for_account(account_id)
2)传递到模板
context = {"transactions":transactions,}
return render(request, "transactions/transactions_for_account.html", context)
3)访问属性,完成
{% for transaction in transactions %}
<tr>
<td class="tg-6k2t">{{ transaction.account }}</td>
<td class="tg-6k2t">{{ transaction.categories }}</td>
<td class="tg-6k2t">{{ transaction.date }}</td>
<td class="tg-6k2t">{{ transaction.payee }}</td>
<td class="tg-6k2t">{{ transaction.comment }}</td>
<td class="tg-6k2t">{{ transaction.outflow }}</td>
<td class="tg-6k2t">{{ transaction.inflow }}</td>
<td class="tg-6k2t">{{ transaction.cleared }}</td>
</tr>
{% endfor %}