Reputation: 8988
DRF serializes by default a filefield or imagefield path to it's relative path.
Like in this questions Django REST Framework and FileField absolute url
I know it's possible to generate a custom field called i.e. "file_url" and serialize the full path.
But is it possible to serialize it in the same field? like:
class Project(models.Model):
name = models.CharField(max_length=200)
thumbnail = models.FileField(upload_to='media', null=True)
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ( 'id' ,'url', 'name', 'thumbnail')
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
{
"id": 1,
"url": "http://localhost:8000/api/v1/projects/1/",
"name": "Institutional",
"thumbnail": "ABSOLUTE URL"
}
Upvotes: 4
Views: 3051
Reputation: 8897
You could override to_representation
method and write an absolute path there:
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ( 'id' ,'url', 'name', 'thumbnail')
def to_representation(self, instance):
representation = super(ProjectSerializer, self).to_representation(instance)
domain_name = # your domain name here
full_path = domain_name + instance.thumbnail.url
representation['thumbnail'] = full_path
return representation
Upvotes: 6