最新要闻

广告

手机

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

iphone11大小尺寸是多少?苹果iPhone11和iPhone13的区别是什么?

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

警方通报辅警执法直播中被撞飞:犯罪嫌疑人已投案

家电

全球热门:基于ModelViewSet写接口

来源:博客园


(资料图片)

基于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 modelsclass 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 listclass Publish(models.Model):    name = models.CharField(verbose_name="出版社名称", max_length=32)    address = models.CharField(verbose_name="出版社地址", max_length=32)    def __str__(self):        return self.nameclass 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//", views.BookView.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),]

四、视图类变得非常简洁

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

关键词: 哈哈哈哈 约束条件 反序列化