快速入手-基于Django-rest-framework的ModelViewSet终极版(七)

发布于:2025-03-31 ⋅ 阅读:(22) ⋅ 点赞:(0)

        和上一节中的代码不通地方做一下说明

1、对应的api模块中的urls.py

导入路由模块,进行相关操作

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

from rest_framework import routers

routers = routers.DefaultRouter()
routers.register("linkapi", views.Linkapi)

app_name = "api"
urlpatterns = []

urlpatterns += routers.urls

2、视图函数类(两种写法)

 

from django.shortcuts import render, HttpResponse


from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import (
    ListModelMixin,
    CreateModelMixin,
    RetrieveModelMixin,
    UpdateModelMixin,
    DestroyModelMixin,
)
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers


from .models import *
from api.serializer import *

# 这种写法实现所有的增删改查,不能够单独进行操作
# class Linkapi(ModelViewSet):
# 不仅可以实现所有的增删改查,而且可以单独也可以全部包含增删改查
class Linkapi(
    GenericViewSet,
    ListModelMixin,
    CreateModelMixin,
    RetrieveModelMixin,
    UpdateModelMixin,
    DestroyModelMixin,
):

    queryset = Link.objects.all()
    serializer_class = LinkSerializer

备注说明:

class Linkapi(ModelViewSet):这种写法实现所有的增删改查,不能够单独进行操作

3、用apifox测试正常。 

4、代码下载

链接: https://pan.baidu.com/s/1d8didPJgWxOl40pLLcX3qQ?pwd=2tcm 提取码: 2tcm 


网站公告

今日签到

点亮在社区的每一天
去签到