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

Django REST框架中父/子产品无法获取Image与Attribute字段

问题解决:Product序列化器中attributes和images字段不显示

问题原因

Django对外键的反向关联默认使用模型名_set(小写)作为关联名称,比如:

  • Attribute模型的外键指向Product,默认反向关联名称是attribute_set
  • ProductImage模型的外键指向Product,默认反向关联名称是productimage_set

你在序列化器中定义的字段名是attributes和images,与默认反向名称不匹配,导致DRF无法找到对应关联数据,因此不会在响应中输出这些字段。

解决方案

方案1:修改模型外键,指定关联名称(推荐)

在models.py中给外键添加related_name参数,让反向关联名称与序列化器中的字段名一致:

class Attribute(models.Model):
    name = models.CharField(max_length=100)
    # 添加related_name='attributes'
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='attributes')
   
 
class ProductImage(models.Model):
    # 添加related_name='images'
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images')
    image = models.ImageField(upload_to='product_images/')

修改后执行数据库迁移:

python manage.py makemigrations
python manage.py migrate

方案2:不修改模型,在序列化器中指定数据源

如果不想修改模型,可以在序列化器的字段中通过source参数指定默认的反向关联名称:

class ChildProductSerializer(serializers.ModelSerializer):
    # 用source指定默认反向名称
    attributes = AttributeSerializer(many=True, read_only=True, source='attribute_set')
    images = ProductImageSerializer(many=True, read_only=True, source='productimage_set')

    class Meta:
        model = Product
        fields = '__all__'

class ProductSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()
    attributes = AttributeSerializer(many=True, read_only=True, source='attribute_set')
    images = ProductImageSerializer(many=True, read_only=True, source='productimage_set')

    class Meta:
        model = Product
        fields = '__all__'

    def get_children(self, obj):
        children = Product.objects.filter(parent_product=obj)
        serializer = ChildProductSerializer(children, many=True)
        return serializer.data

额外检查

确保你已经为目标Product实例创建了对应的Attribute和ProductImage数据,否则即使字段配置正确,也不会有内容输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:52:43