Django系列之DRF简单使用

基于ModelViewSets的简单使用

models.py

from django.db import models

class AuthorDetail(models.Model):
    gender = models.CharField(max_length=8)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)

class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    ad = models.OneToOneField(AuthorDetail, on_delete=models.CASCADE, null=True)

    def __str__(self):
        return self.name

serializers.py

from rest_framework import serializers

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = "__all__"
        
        # 检验条件
        extra_kwargs = {
            "age": {"min_value": 0, "max_value": 200}
        }

app01/views.py

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from app01.models import Author
from app01.serializers import AuthorSerializer

class AuthorModelViewsets(ModelViewSet):

    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

    @action(methods=["get"], detail=False)          # detail=False or True: True: 系统会自动在生成的路由中添加pk值
    def top3(self, request):
        top3 = self.queryset.order_by("-age")[:3]
        serializer = AuthorSerializer(instance=top3, many=True)
        return Response(serializer.data)

    @action(methods=["get"], detail=True)       # 如果视图逻辑中需要pk值,detail就得是True
    def detailone(self, request, pk):
        author_detail = Author.objects.get(pk=pk)
        print(author_detail)
        return Response({"name": author_detail.name, "age": author_detail.age})

project/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("league/", include("app01.urls")),
]

app01/urls.py

from rest_framework.routers import SimpleRouter

from app01.views import AuthorModelViewsets

urlpatterns = []

router = SimpleRouter()
router.register("author", AuthorModelViewsets)

urlpatterns += router.urls

使用 SimpleRouter() 可以帮我们实现五个基础的 action 方法:
{“get”: “list”, “post”: “create”, “get/id”: “retrieve”, “put”: “update”, “delete”: “`destroy”}

如果需要增加一些其他的路由视图,就需要用 action 声明了。

action声明

如果需要增加一些其他自定义视图函数,则需要使用到 action 装饰器:

from rest_framework.decorators import action

@action(methods=["get"], detail=False)
def top3(self, request):
	...

@action(methods=["get"], detail=True)
def detailone(self, request, pk):
        ...

detail 参数: True or False,如果视图中需要用到pk值,那就让 detail=True
True:系统会自动在生成的路由中添加pk值,比如
Django系列之DRF简单使用_第1张图片
False:不会添加pk值到路由中。

你可能感兴趣的:(django,sqlite,数据库)