[英]Django - get model object attributes from ModelForm
我有一個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獲取對象並將我想要的信息存儲在列表中,然后從模板中將其拉出來,但這對我來說似乎相當可怕。
有沒有更好的方法來做到這一點?
感謝評論,我發現我正在做的事情非常愚蠢和無意義。
這有效:
1)獲取所有Transaction對象
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 %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.