Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework 'RelatedManager' object has no attribute

The original error is:

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'.

This is my 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)

The serializers:

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",)

And in the view:

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

Why do I get the error RelatedManager' object has no attribute 'original' ? The reverse relationship ProductImage, with related_name="images" does have the attribute original.

like image 879
Alejandro Veintimilla Avatar asked Oct 21 '16 22:10

Alejandro Veintimilla


1 Answers

If you have nested serializers and you're expecting more than one, you should add the many=True otherwise DRF will treat the manager as the object.

like image 100
DelGiudice Avatar answered Nov 11 '22 14:11

DelGiudice