DRF - format 访问 json 数据

urls.py:

from django.urls import path, re_path
from drf import views

urlpatterns = [
    path('view/', views.TestView.as_view({"get": "list"})),
]

views.py:

from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from drf import models


class PagerSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Role
        fields = "__all__"


class TestView(ModelViewSet):
    queryset = models.Role.objects.all()  # 数据
    serializer_class = PagerSerializer  # 序列化
    pagination_class = PageNumberPagination  # 分页

访问 /view/

加上 format 参数来访问 json 数据,访问 /view/?format=json,即转为 json 数据

修改 urls.py 实现

from django.urls import path, re_path
from drf import views

urlpatterns = [
    re_path('view\.(?P<format>\w+)$', views.TestView.as_view({"get": "list"})),
]

访问 /view.json

 

posted @ 2021-01-20 21:08  Sch01aR#  阅读(361)  评论(0编辑  收藏  举报