Django - 从ModelForm获取模型对象属性

3

我有一个 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获取对象并将我想要的信息存储在列表中,然后在模板中从那里提取它,但这对我来说似乎相当可怕。
有更好的方法吗?

我不明白你在问什么。那些嵌套的ifequal / ifnotequal语句是用来干什么的?而__str__是模型多选字段的默认表示,这就是你的多对多字段在表单上将使用的内容;你是否尝试过直接使用 {{ field }} - Daniel Roseman
{{ field }}对于类别给我一个选择框,对于账户则是不同账户的下拉菜单,我想要显示所选的账户(无需下拉菜单)和所选的类别(无需选择)。我不想输入任何更改/信息,只想将Transaction的所有属性作为文本显示。 - Lomtrur
2
那么你为什么要使用表单? - Daniel Roseman
1个回答

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 %}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接