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

Django模型__str__方法:关联外键对象名称显示问题

解决Django后台ProductImage显示关联Product名称的问题

嘿,这个问题其实很容易搞定,只需要调整ProductImage模型里的__str__方法,让它返回关联产品的名称就行啦!

直接修改现有代码的方案

你当前的ProductImage模型里,外键字段是product_id,直接通过这个字段访问关联Product对象的name属性就可以:

class ProductImage(models.Model):
    image_addr = models.FileField(upload_to='products/')
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
    
    def __str__(self):
        # 返回关联产品的名称
        return self.product_id.name

修改后,Django后台里的ProductImage对象就会显示对应产品的名称,比如你提到的iPhone X啦。

额外的优化建议

顺便提一句,Django里外键字段的命名惯例是不用加_id后缀的——因为Django会自动在数据库表中生成以_id结尾的列来存储关联ID。把外键字段名改成product,代码可读性会更好:

class ProductImage(models.Model):
    image_addr = models.FileField(upload_to='products/')
    # 字段名改为product,符合Django惯例
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.product.name

如果想要显示更详细的信息(比如图片文件名),还可以用f-string组合起来:

def __str__(self):
    return f"{self.product.name} - {self.image_addr.name}"

这样后台里就能看到类似“iPhone X - iphone_x_main.jpg”的详细名称啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:22:14