Return image url in Django Rest Framework

后端 未结 4 2206
孤街浪徒
孤街浪徒 2020-12-31 11:05

I am using Django Rest Framework and have the following model:

class Picture(models.Model):
    some_field = models.ForeignKey(some_model)
    image = models         


        
4条回答
  •  我在风中等你
    2020-12-31 11:29

    Provided answers are all correct, But I want to add a point to answers, and that is a way to return the path of the file including the address of the site. To do that, we get help from the request itself:

    class PictureSerialiser(serializers.ModelSerializer):
    
        image_url = serializers.SerializerMethodField('get_image_url')
    
        class Meta:
            model = Picture
            fields = ('field',
                      'image',
                      'image_url')
    
        def get_image_url(self, obj):
            request = self.context.get("request")
            return request.build_absolute_uri(obj.image.url)
    

提交回复
热议问题