使用视图组件进行接口优化
-
使用视图组件的generics进行接口逻辑优化
-
导入generics
from rest_framework import generics
-
定义序列化类
class BookSerializer(serializers.ModelSerializer):class Meta:model = 指定模型类fields = (指定验证字段)extra_kwargs = {"field_name":{"write_only":True}}
-
导入序列化类
from .app_serializers import BookSerializer
-
定义视图类
class BookView(generics.ListCreateAPIView):queryset = BookInfo.objects.all()serializer_class = BookSerializer
GET获取全部数据和POST新增一条数据案列
-
建立url
re_path(r"^books/$", BookView.as_view()),
-
建立model
from django.db import modelsfrom datetime import datetime
class AuthorInfo(models.Model):name = models.CharField(max_length=32, verbose_name="作者名称")age = models.IntegerField(verbose_name="作者年龄")class Meta:db_table = "db_author_info"verbose_name = "作者信息"verbose_name_plural = verbose_namedef __str__(self):return self.nameclass PublishInfo(models.Model):name = models.CharField(max_length=32, verbose_name="出版社名称")city = models.CharField(max_length=32, verbose_name="出版社所在城市")email = models.EmailField(verbose_name="出版社邮箱")class Meta:db_table = "db_publish_info"verbose_name = "出版社信息"verbose_name_plural = verbose_namedef __str__(self):return self.nameclass BookInfo(models.Model):title = models.CharField(max_length=32, verbose_name="书名")publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")publish = models.ForeignKey(PublishInfo, related_name="book", related_query_name="book_query", on_delete=models.CASCADE, verbose_name="出版社")authors = models.ManyToManyField(AuthorInfo, verbose_name="图书作者")class Meta:db_table = "db_book_info"verbose_name = "图书信息"verbose_name_plural = verbose_namedef __str__(self):return self.title
-
导入generics
from rest_framework import generics
-
定义序列化类
from.models import BookInfo
from rest_framework import serializersclass BookSerializer(serializers.ModelSerializer):class Meta:model = BookInfofields = ("title","price","publishDate","publish","authors","author_list","publish_name","publish_city")extra_kwargs = {"publish": {"write_only": True},"authors": {"write_only": True}}publish_name = serializers.CharField(max_length=32, read_only=True, source="publish.name")publish_city = serializers.CharField(max_length=32, read_only=True, source="publish.city")author_list = serializers.SerializerMethodField()def get_author_list(self, book_obj):authors = []for author in book_obj.authors.all():authors.append(author.name)return authors
-
导入序列化类
from .app_serializers import BookSerializer
-
定义视图类
from rest_framework import genericsfrom .models import BookInfo, PublishInfo, AuthorInfo
from .app_serializers import BookSerializerclass BookView(generics.ListCreateAPIView):queryset = BookInfo.objects.all()serializer_class = BookSerialize
-
postman的GET请求所有数据
-
postman的POST请求所有数据
使用视图组件进行接口优化
-
使用视图组件的generics进行接口逻辑优化
-
导入generics
from rest_framework import generics
-
定义序列化类
class BookSerializer(serializers.ModelSerializer):class Meta:model = 指定模型类fields = (指定验证字段)extra_kwargs = {"field_name":{"write_only":True}}
-
导入序列化类
from .app_serializers import BookSerializer
-
定义视图类
class BookFilterView(generics.RetrieveUpdateDestroyAPIView):queryset = BookInfo.objects.all()serializer_class = BookSerializer
GET获取一条数据和PUT修改一条数据和DELETE删除一条数据案列
-
建立url
re_path(r"^books/(?P\d+)/$", BookFilterView.as_view())
-
正则不取名叫pk会报一个Expected view BookFilterView to be called with a URL keyword argument named “pk”.的错误
-
建立model
from django.db import modelsfrom datetime import datetime
class AuthorInfo(models.Model):name = models.CharField(max_length=32, verbose_name="作者名称")age = models.IntegerField(verbose_name="作者年龄")class Meta:db_table = "db_author_info"verbose_name = "作者信息"verbose_name_plural = verbose_namedef __str__(self):return self.nameclass PublishInfo(models.Model):name = models.CharField(max_length=32, verbose_name="出版社名称")city = models.CharField(max_length=32, verbose_name="出版社所在城市")email = models.EmailField(verbose_name="出版社邮箱")class Meta:db_table = "db_publish_info"verbose_name = "出版社信息"verbose_name_plural = verbose_namedef __str__(self):return self.nameclass BookInfo(models.Model):title = models.CharField(max_length=32, verbose_name="书名")publishDate = models.DateField(default=datetime.now, verbose_name="出版日期")price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="图书价格")publish = models.ForeignKey(PublishInfo, related_name="book", related_query_name="book_query", on_delete=models.CASCADE, verbose_name="出版社")authors = models.ManyToManyField(AuthorInfo, verbose_name="图书作者")class Meta:db_table = "db_book_info"verbose_name = "图书信息"verbose_name_plural = verbose_namedef __str__(self):return self.title
-
导入generics
from rest_framework import generics
-
定义序列化类
from.models import BookInfo
from rest_framework import serializersclass BookSerializer(serializers.ModelSerializer):class Meta:model = BookInfofields = ("title","price","publishDate","publish","authors","author_list","publish_name","publish_city")extra_kwargs = {"publish": {"write_only": True},"authors": {"write_only": True}}publish_name = serializers.CharField(max_length=32, read_only=True, source="publish.name")publish_city = serializers.CharField(max_length=32, read_only=True, source="publish.city")author_list = serializers.SerializerMethodField()def get_author_list(self, book_obj):authors = []for author in book_obj.authors.all():authors.append(author.name)return authors
-
导入序列化类
from .app_serializers import BookSerializer
-
定义视图类
from rest_framework import generics
from .models import BookInfo, PublishInfo, AuthorInfo
from .app_serializers import BookSerializer
class BookFilterView(generics.RetrieveUpdateDestroyAPIView):queryset = BookInfo.objects.all()serializer_class = BookSerializer
8. postman的GET请求获取一条数据![在这里插入图片描述](https://img-blog.csdnimg.cn/20190725194302119.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDEzMTRsb3Zlenlm,size_16,color_FFFFFF,t_70)
9. postman的PUT请求修改一条数据![在这里插入图片描述](https://img-blog.csdnimg.cn/20190725194323649.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDEzMTRsb3Zlenlm,size_16,color_FFFFFF,t_70)
- postman的DELETE请求删除一条数据