![](/img/trans.png)
[英]Django REST framework GET nested serializer produces an error: 'RelatedManager' object has no attribute 'datafile_set'"
[英]Django Rest Framework 'RelatedManager' object has no attribute
原始錯誤是:
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
屬性。
如果您有嵌套的序列化程序並且您期望多個,則應添加many=True
否則DRF會將管理器視為對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.