【发布时间】:2017-03-04 08:18:32
【问题描述】:
原来的错误是:
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' ? ProductImage 与related_name="images" 的反向关系确实具有original 属性。
【问题讨论】:
-
你在
images = ProductImageSerializer(required=False, many=True)上缺少many=True
标签: django django-rest-framework