首页 > 其他分享 >基于ModelViewSet写接口

基于ModelViewSet写接口

时间:2023-02-11 19:11:30浏览次数:59  
标签:__ 基于 name models list self ModelViewSet 接口 length

基于ModelViewSet写接口

​ 一旦继承该类写接口,那么路由的写法就变了,好处是五个接口不用分两个视图类写尤其是查询所有和查询单个数据的也可以写到同一个视图类里面了。路由变成.as_view({'get': 'list'}),路由做映射,意思是如果get请求,访问这个地址,就执行视图类的list方法。

from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet  # 导入语句

一、序列化类没有发生变

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        # 跟book表有强关联
        model = Book
        # fields = ['写需要序列化的字段名',[]···]
        # 如果fields = '__all__'这样写就表明序列化所有字段
        fields = '__all__'
        # extra_kwargs = {'字段名': {'约束条件': 约束参数},是反序列化字段
        extra_kwargs = {'name': {'max_length': 8},
                        'publish_detail': {'read_only': True},
                        'authors_list': {'read_only': True},
                        'publish': {'write_only': True},
                        'authors': {'write_only': True}
                        }

    def validate_name(self, name):
        if name.startswith('sb'):
            raise ValidationError('书名不能以sb开头')
        else:
            return name

二、表模型的代码没变哦

from django.db import models


class Book(models.Model):
    name = models.CharField(verbose_name='书名', max_length=32)
    price = models.CharField(verbose_name='价格', max_length=32)

    def __str__(self):
        return self.name

    # 外键 书跟出版社是一对多
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    # 外键 书跟作者是多对多
    authors = models.ManyToManyField(to='Author')

    def publish_detail(self):
        return {'name': self.publish.name, 'address': self.publish.address}

    def author_list(self):
        list = []
        for author in self.authors.all():
            list.append({'name': author.name, 'phone': author.phone})
        return list


class Publish(models.Model):
    name = models.CharField(verbose_name='出版社名称', max_length=32)
    address = models.CharField(verbose_name='出版社地址', max_length=32)

    def __str__(self):
        return self.name


class Author(models.Model):
    name = models.CharField(verbose_name='作者姓名', max_length=32)
    phone = models.CharField(verbose_name='电话号码', max_length=11)

    def __str__(self):
        return self.name

三、路由写法变成了映射

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]

image

四、视图类变得非常简洁

from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from .models import Book
from .serializer import BookSerializer

class BookView(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    
    
"""
ReadOnlyModelViewSet继承了这个类只有两个功能
一个是查询所有数据, 另一个是查询单个数据
代码变少的同时还不忘做个性化哈哈哈哈
"""

image

标签:__,基于,name,models,list,self,ModelViewSet,接口,length
From: https://www.cnblogs.com/almira998/p/17112378.html

相关文章