You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django新手求助:如何访问外键字段并在前端显示关联值

解决Django外键关联字段显示主键而非对应值的问题

方法一:模板中直接访问关联对象的字段

修改你的HTML模板,把{{ spend.spendCurrency }}替换为关联模型的currCode字段:

{% for spend in spend_list %}
    <tr>             
        <td>{{ spend.spendAmount }}</td>
        <td>{{ spend.spendCurrency.currCode }}</td>
    </tr>
{% endfor %}

注:模板里原用的<th>标签通常用于表头,表格数据建议改用<td>更规范。

方法二:给Currency模型定义__str__方法

在Currency模型中添加__str__方法,指定对象的默认显示值:

class Currency(models.Model):
    currCode = models.CharField('Currency',max_length=3)
    currName = models.CharField('Name',max_length=100)

    def __str__(self):
        return self.currCode  # 返回需要显示的字段值

修改后,模板里原来的{{ spend.spendCurrency }}会自动显示currCode内容(如EUR),无需改动模板代码。

补充说明

Django中输出模型对象时,默认调用其__str__方法的返回值;如果未定义该方法,会显示对象的主键值。方法一适合仅当前场景的需求,方法二更通用,后续任何地方输出Currency对象都会显示指定字段。

内容的提问来源于stack exchange,提问作者hobscrk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 05:35:03