'Reverse Relationship Django Rest Framework

i have this serializer of a Photo, that translates uploaded photos to URL

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

And this serializer is based on a model that's connected to Entity Model reverse relationship.

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, null=False, related_name='entity_photo')
    image = models.FileField(upload_to='entities/')
    created_at = models.DateTimeField(editable=False, default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)

The class Entity

class Entity(models.Model):

Has no fields connecting to EntityPhotos, but i'd like to add the photos to Entity Serializer

class EntityCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Entity
        fields = '__all__'

And i would like to show the EntityPhotos that have Entity_id=pk from url. So that whenever i make a get request to entity/1 i want to see also the photos that have entity_id == 1. Do you have any idea how to do that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source