我有一个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 ()方法)。
我能看到的唯一方法是迭代FormSet,获取Account和Category对象的ID,通过Id获取对象并将我想要的信息存储在列表中,然后从那里拉出来在模板中,但这对我来说似乎相当可怕。
有更好的方法吗?
答案 0 :(得分:0)
感谢这些评论,我发现我所做的事情非常愚蠢而毫无意义。
这有效:
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 %}