" name="sm-site-verification"/>
侧边栏壁纸
博主头像
PySuper博主等级

千里之行,始于足下

  • 累计撰写 203 篇文章
  • 累计创建 14 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
Web

Django 函数视图、类视图、视图集

PySuper
2020-07-14 / 0 评论 / 0 点赞 / 6 阅读 / 4040 字
温馨提示:
所有牛逼的人都有一段苦逼的岁月。 但是你只要像SB一样去坚持,终将牛逼!!! ✊✊✊

仅记录个人学习,如有不同,欢迎指导

函数视图: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

urls.py

urlpatterns = [
    url('^user/$', UserDetailView.as_view()),
]

views.py

class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

视图集:ViewSet

serializers.py

class FrequencySerializer(serializers.ModelSerializer):

    class Meta:
        model = Frequency
        fields = ['id', 'name']

views.py

class FrequencyViewSet(viewsets.ModelViewSet):
    queryset = Frequency.objects.all()
    serializer_class = FrequencySerializer

urls.py

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")
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区