在Django Rest中保存文件有多种方法,下面我将介绍其中两种常用的方法。
方法一:使用Django自带的文件字段
from django.db import models
class MyModel(models.Model):
file = models.FileField(upload_to='uploads/')
在这个例子中,文件将被保存在项目根目录下的uploads文件夹中。
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'file')
from rest_framework import views
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from .serializers import MyModelSerializer
class FileUploadView(views.APIView):
parser_classes = (MultiPartParser, FormParser)
def post(self, request, format=None):
serializer = MyModelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
else:
return Response(serializer.errors, status=400)
在这个例子中,我们使用MultiPartParser和FormParser来解析请求中的文件数据。
from django.urls import path
from .views import FileUploadView
urlpatterns = [
path('upload/', FileUploadView.as_view()),
]
现在,你可以通过发送POST请求到/upload/
来上传文件了。
方法二:使用第三方库
django-rest-framework
和django-rest-framework-filters
包:pip install djangorestframework django-filter
from django.db import models
class MyModel(models.Model):
file = models.FileField(upload_to='uploads/')
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'file')
from rest_framework import viewsets
from .serializers import MyModelSerializer
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import MyModelViewSet
router = DefaultRouter()
router.register(r'mymodels', MyModelViewSet)
urlpatterns = [
path('', include(router.urls)),
]
现在,你可以通过发送POST请求到/mymodels/
来上传文件了,并且还可以通过GET请求获取文件列表、PUT请求更新文件等。
以上是两种在Django Rest中保存文件的方法,你可以根据具体需求选择适合自己的方法进行文件保存。
领取专属 10元无门槛券
手把手带您无忧上云