【问题标题】:Django Rest Framework 'RelatedManager' object has no attributeDjango Rest Framework 'RelatedManager' 对象没有属性
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 这是一个很棒的答案。你拯救了我的一天!
  • 我第二次看到你的答案..我赞成并保存了。
猜你喜欢
  • 1970-01-01
  • 2015-10-15
  • 2019-04-30
  • 1970-01-01
  • 2021-05-02
  • 2018-09-13
  • 2020-12-24
  • 1970-01-01
  • 2019-04-06
相关资源
最近更新 更多