目录
基于九个视图子类写五个接口
编写代码的过程中代码的可用性越来越强、封装程度越来越高级、程序员需要写的代码越来越少而能干的事情就越来越多。这或许是看源码分析的魅力吧,果然代码改变世界。加油吧年轻人。好好学习。代码也让你改变改变,变得小富婆哈哈哈哈,那接下来研究九个视图子类之前先罗列一下那九个视图子类吧!首先注意不用跟GenericAPIView配合使用,直接导入模块继承使用即可,就会有某个或某几个接口。其实也算是更加接近完善的过程,因为不需要依赖GenericAPIView,成立独立了,而且原本五个的基础上又丰富起来了,其实没有创造出新的接口方法而是原有的五个进行排列组合的方法从而变得更加个性化了。几乎满足现有的基本需求了。用的数据和序列化组件是一样的,路由也是一样的。因为研究重点是我们的九个视图子集嘛!
- 查询所有 ListAPIView
- 新增数据 CreateAPIView
- 删除数据 DestroyAPIView
- 修改数据 UpdateAPIView
- 查询单个 RetrieveAPIView
- 查询所有新增数据 ListCreateAPIView
- 查询单个删除数据 RetrieveDestroyAPIView
- 查询单个修改数据 RetrieveUpdateAPIView
- 查询单个修改删除数据 RetrieveUpdateDestroyAPIView
# 导入九个视图子集
from rest_framework.generics import CreateAPIView, DestroyAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView,
RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView, UpdateAPIView
一、准备工作把模型表、序列化类、路由代码贴上去吧
# 模型表代码
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
# 序列化类代码
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.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('books/', views.BookView.as_view()),
path('books/<int:pk>/', views.BookDetailView.as_view()),
二、通过九个视图写接口
from rest_framework.generics import CreateAPIView, DestroyAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView, \
RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView, UpdateAPIView
from .models import Book
from .serializer import BookSerializer
class BookView(ListCreateAPIView):
'''查所有 新增数据'''
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetailView(RetrieveUpdateDestroyAPIView):
'''查单个 修改 删除 数据'''
queryset = Book.objects.all()
serializer_class = BookSerializer
总结:继承九个视图子集写接口代码的量确实变少了,路由也是传统的写法,但是还是需要写两个视图类实现。
标签:__,name,models,子类,self,接口,视图,class From: https://www.cnblogs.com/almira998/p/17111931.html