Home > Software design >  AttributeError: 'Model' object has no attribute '....' Django Rest Framework
AttributeError: 'Model' object has no attribute '....' Django Rest Framework

Time:02-13

I have this model

class EntityPhoto(models.Model):
    user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo_user')
    entity = models.ForeignKey('Entity', on_delete=models.CASCADE)
    image = models.FileField(upload_to='entities/')
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)
class Entity(models.Model):
....
class EntityPhotosSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField('get_img')

    def get_img(self, entity_photo):
        if not entity_photo.image:
            raise NotFound

        request = self.context.get('request')
        return request.build_absolute_uri(entity_photo.image.url)


    class Meta:
        model = EntityPhoto
        fields = ('user', 'entity', 'image',)


class SpecialistSerializer(serializers.ModelSerializer):
    reviews_quantity = serializers.IntegerField(source="get_reviews_quantity")

    class Meta:
        model = Entity
        fields = '__all__'

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['photos'] = EntityPhotosSerializer(many=True, instance=instance.image_set.all()).data
        return data

and after making get request I get an error:

AttributeError: 'Entity' object has no attribute 'image_set'

Which is weird because a few days ago i did the same thing with a model that was connected via reverse relationship the same way, i even copied the code and it worked. Do you think it might be because of the image file? I wanna show the list of Photos(that the serializer changed to url) for every Entity Instance.

CodePudding user response:

You are trying to access to "image_set" but there is no "image" model linked to Entity. However, there is a EntityPhoto model.

So doing

data['photos'] = EntityPhotosSerializer(many=True,instance=instance.image_set.all()).data

is not supposed to give anything.

If you want to access to the related entity photo of the entity, you are supposed to do

data['photos'] = EntityPhotosSerializer(many=True,instance=instance.entityphoto_set.all()).data
  • Related