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值,比如
在这里插入图片描述
False:不会添加pk值到路由中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值