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

Django中IndexProduct类__str__方法返回Subcategory显示异常问题

解决多对多字段在__str__中显示异常的问题

问题根源

  1. Category模型缺失存储分类值的字段,且未定义__str__方法,无法正确展示分类名称
  2. 直接调用str(self.Subcategory)获取的是多对多管理器对象的标识,而非实际关联的分类数据

修复步骤

1. 完善Category模型

给Category添加存储分类的字段和__str__方法,确保分类对象能输出友好名称:

class Category(models.Model):
    CHOICES = (
        ('Accessories','Accessories'),
        ('Fashions','Fashions')
    )
    # 添加字段存储分类选项值
    name = models.CharField(max_length=20, choices=CHOICES)

    def __str__(self):
        # 返回分类名称
        return self.name

2. 修改IndexProduct的__str__方法

通过all()方法获取多对多关联的所有分类对象,拼接成可读字符串:

class IndexProduct(models.Model):
    Title = models.CharField(max_length=50)
    Subcategory = models.ManyToManyField(Category)

    def __str__(self):
        # 遍历所有关联分类,拼接成字符串
        category_list = [str(cat) for cat in self.Subcategory.all()]
        # 处理无关联分类的情况,避免显示None
        categories = ", ".join(category_list) if category_list else "无分类"
        return f"{self.Title}--**{categories}**"

效果说明

修复后,当产品关联分类时会显示类似:

Adidas Shoes blue color--**Fashions**

未关联分类时会显示:

NEW ITEM--**无分类**

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:02:18