仅记录个人学习,如有不同,欢迎指导
函数视图:function
函数视图是三者中,最简单粗暴的,直接接受参数,然后一步一步处理业务逻辑,最后return JsonResponse()。
只要返回给前端一个json数据,就可以了…
def upload(request):
descriptions = Description.objects.all()
for i in descriptions:
print(i.name)
data = {
"descriptions": descriptions,
}
return render(request, "audio_upload.html", data)
类视图
View
当我们使用View
,我们可以根据请求方式,选择我们要执行的函数视图
但是这里的返回值:Response(data=None, status=None, template_name=None, headers=None, exception=False, content_type=None)
class LogoutView(View):
def get(self, request):
logout(request)
return render(request, 'login.html')
APIView
urlpatterns = [
url('^user/$', UserDetailView.as_view()),
]
class UserDetailView(RetrieveAPIView):
serializer_class = UserDetailSerializer
permission_classes = [IsAuthenticated]
def get_object(self):
return self.request.user
视图集:ViewSet
class FrequencySerializer(serializers.ModelSerializer):
class Meta:
model = Frequency
fields = ['id', 'name']
class FrequencyViewSet(viewsets.ModelViewSet):
queryset = Frequency.objects.all()
serializer_class = FrequencySerializer
router = DefaultRouter()
router.register(r'^frequency', FrequencyViewSet)
urlpatterns += router.urls
重写ModelViewSet
# 获取用户数据: router.register(r'^user_name', UserInfoViewSet)
class UserFileViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('-id')
serializer_class = UserFileSerializer
def retrieve(self, request, *args, **kwargs):
"""返回指定用户数据,instance是url后的user_id"""
instance = self.get_object()
items = Fileinfo.objects.filter(author=instance)
items = json.loads(dc_serializers.serialize("json", items)) # 序列化
return Response(data=items)
def destroy(self, request, *args, **kwargs):
instance = self.get_object() # username
file_list = request.POST.get("file_list", None) # 用别名反向查询
for file_id in file_list:
file = Fileinfo.objects.get(id=file_id)
file.delete()
return Response(data="items")
评论区