Django Rest Framework' RelatedManager'对象没有属性

时间:2016-10-21 22:54:01

标签: django django-rest-framework

原始错误是:

Got AttributeError when attempting to get a value for field `original` on serializer `ProductImageSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance.
Original exception text was: 'RelatedManager' object has no attribute 'original'.

这是我的models.py

class Product(models.Model):

    name = models.CharField(max_length=100, db_index=True)
    ean = models.CharField(max_length=13, db_index=True)

    ...

class ProductImage(models.Model):
    product = models.ForeignKey(Product, null=True, related_name='images', on_delete=models.CASCADE, db_index=True)
    original = models.ImageField(upload_to=get_uuid_image)
    medium = models.ImageField(upload_to=get_uuid_image)
    small = models.ImageField(upload_to=get_uuid_image)

序列化器:

class ProductBasicSerializer(serializers.ModelSerializer):
    tags = TagSerializer(many=True)
    brand = BrandSerializer()
    images = ProductImageSerializer(required=False)

    class Meta:
        model = Product
        fields = ['tags', 'brand', "ean", "name", "quantity", "unit", "images"]


class ProductImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = ProductImage
        exclude = ("product",)

在视图中:

product = Product.objects.get(ean=ean)
serializer = ProductBasicSerializer(product)

为什么我收到错误RelatedManager' object has no attribute 'original'?具有related_name="images"的反向关系ProductImage具有属性original

1 个答案:

答案 0 :(得分:26)

如果您有嵌套的序列化程序并且您期望多个,则应添加many=True否则DRF会将管理器视为对象。