我有一个 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对象的Ids,通过它们的Id获取对象并将我想要的信息存储在列表中,然后在模板中从那里提取它,但这对我来说似乎相当可怕。
有更好的方法吗?
__str__
是模型多选字段的默认表示,这就是你的多对多字段在表单上将使用的内容;你是否尝试过直接使用{{ field }}
? - Daniel Roseman