Django REST Framework (DRF)'s FileField behave differently in generics view and APIView

I want handle file upload in django.

The Model and Serializer are as follow:

def save_file(instance, filename):
    _, ext = os.path.splitext(filename)
    return f"{instance.id}{ext}"

class FileModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=64)
    file = models.FileField(upload_to=save_file)
    created = models.DateTimeField(auto_now_add=True)


class FileModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = FileModel
        fields = "__all__"

When I use generics view like this:

class FileListApi(generics.ListAPIView):
    queryset = FileModel.objects.all()
    serializer_class = FileModelSerializer

The API will be like this, the url is absolute path:

[
  {
    "id": "2c5488ec-7b5d-45ab-9c43-058c19d76626",
    "title": "file.png",
    "file": "http://127.0.0.1:8000/media/2c5488ec-7b5d-45ab-9c43-058c19d76626.png",
    "created": "2024-02-07T02:29:29.845808Z"
  }
]

However when I use APIView:

class FileListApi(APIView):
    def get(self, request):
        serializer = FileModelSerializer(FileModel.objects.all(), many=True)
        return Response(serializer.data)

The url is now relative path:

[
  {
    "id": "2c5488ec-7b5d-45ab-9c43-058c19d76626",
    "title": "file.png",
    "file": "/media/2c5488ec-7b5d-45ab-9c43-058c19d76626.png",
    "created": "2024-02-07T02:29:29.845808Z"
  }
]

I can image there will be situations that require absolute path or relative path, in my particular case I want to use relative path.

Why DRF behave differently in generics view and APIView?

How to make DRF output url differently?

Back to Top