drf9个视图子类,2个视图集,路由系统,认证组件

上周内容大回顾

前后端开发模式

前后端混合模式
	1.前端写好交给后端用后端模板语法,把数据补上去
    2.前后端全栈,都有一个人写
前后端分离
	1.前端写前端,后端就只写接口
    2.全栈,前端用现成的框架(vue,react),后端用python,java,c...语言写后端接口就行,通过http调后端

api接口

	通过网络,规定前后台交互信息的规则,也就是前后交互的媒介

接口测试工具:POSTMAN

restful规范

1.接口使用https协议传输,保证数据安全性
2.接口中带api标识
3.接口中带版本标识,多版本共存
4.接口地址即资源,尽量使用名词,不要使用动词,特殊情况写可以使用,
5.资源操作,根据请求方式决定(method:get,post,put,....)
6.接口中含有过滤条件
7.响应数据有状态码
	两种
    1.http响应状态码
    2.自定义响应状态码
8.响应数据带有错误信息
9.响应数据应该遵循返回规范
	查所有,返回查询所有数据对象
    查一个,返回查询数据对象
    新增一个,返回新增数据对象
    修改一个,返回修改数据对象
    删除一个,返回空数据
10.返回数据中带链接

drf介绍,快速使用

drf帮助我们快速写出符合restfull规范的接口
drf最新支持道django3.x及以上版本

cbv执行流程

切入点视图类.as_view()》》到view类中的,as_view方法,返回内部view函数方法内存地址》》路由匹配成功执行viwe(),执行dispatch()方法,》》自己的视图类中没有,找到view中的dispatcht方法,用反射拿出对应的请求方法执行,返回返回值。

APIView执行流程

切入点视图类.as_view()》》到APIView类中的.as_view(),去到父类中view类中,拿到view,
1.取消csrf校验2
2.重写包装了request请求变成了rest_framerwork中的request
3.三大认证,认证,权限,频率,按顺序执行
4.全局异常捕获

Request对象源码

1.重写包装了request,把旧的request放到了request._request中 __getattr__()反射拿request中的数据跟之前用法一样
2.request的属性,request.data,request.query_parms,request.FilES,

序列化和反序列化

核心就是数据格式之间的转换
重模型类数据库中,查数据得到对象,序列化成json格式后给前端
前端传来的json数据,反序列化,插入模型数据库中

序列化组件》》写继承类,实例化得到的对象

常用字段:max_length,required,error_message
做序列化
	序列化实例对象》》对象》》传入要序列化的数据,many=True针对是queryser对象要加》》request.data
    定制化字段
    source
    下面两种的只能用于序列化,不能用在反序列化中
    SerializerMethodFiled
    在模型表中写方法
    ListField
    DictField
做反序列化
	新增
    	序列化类实例化--》对象--》》传入前端的数据》》数据校验》ser.save
        数据校验:字段自己,validators=[方法],局部钩子,全局钩子
   保存
		序列化类实例化--》对象--》》传入前端的要修改的数据》数据校验》ser.save
        数据校验:字段自己,validators=[方法],局部钩子,全局钩子
   重点:
		有时候,序列化字段和反序列化字段,不一样
    	定制的序列化字段,不能用来反序列化
        read_only和write_only的使用
   数据校验
		字段自己】
    	validators
    	局部
       	全局
   ModelSerializer,跟表有关系
		大部分不用重写create,update方法
    	字段可以映射过来,字段参数有的也可以映射过来
        重写字段
        给字段类传参数---》extra_kwargs={'name':{'read_only':True}}
        定制字段跟之前一模一样
        fields列表,必须要有所有字段(序列化,反序列化都要注册)》不一定是表模型字段
       	

请求与响应

request源码
能够解析的编码格式
	全局配置
    项目全局配置
    视图类局部配置
    form-data,urlencode,json
reponse源码
能够响应的编码格式
	全局配置
    项目全局配置
    视图类局部配置
    json, browar
    
drf向响应头中写数据
	headers={}
原生django向响应头中写数据
四板斧都可以,render,redirect,HttpReponse,JsonReponse
obj=HttpResponse()--->obj['server']='nginx'

视图 View

1.两个视图基类
	from rest_framework.views import APIView
    from rest_framework.generics import GenericAPIView
	APIView,GenericAPIView(继承APIView)
2.五个视图扩展类,不能单独使用,需要配合GenericAPIView使用
	from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
	CraeteModelMixin
    ListModelMixin
    RetrieveModelMixin
    DestoryModelMixin
    UpdateModelMixin
3.九个视图子类
	from rest_framework.generics import CreateAPIView,ListAPIView,RetrieveAPIView,UpdateAPIView,DestroyAPIView,ListCreateAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView,RetrieveUpdateDestroyAPIView
    
    
    
    CreateAPIView					新增一个
    ListAPIView						查所有
    RetrieveAPIView					查一个
    UpdateAPIView					修改一个
    DestroyAPIView					删除一个
    ListCreateAPIView				查所有新增一个
    RetrieveUpdateAPIView			查单个新增一个
    RetrieveDestroyAPIView			查所有删除一个
    RetrieveUpdateDestroyAPIView	查所有修改一个新增一个
4.视图集

	from rest_framework.viewsets import ReadOnlyModelViewSet,ViewSet,ViewSetMixin,ModelViewSet,GenericViewSet


	ModelViewSet=五个视图扩展类+GenericViewSet
    ReadOnlyModelViewSet=ListModelMixin,RetrieveModelMixin+GenericViewSet
    
    ViewSetMixin
	ViewSet=ViewSetMixin+APIView
    GenericViewSet=ViewSetMixin+GenericAPIView
-两个视图基类:APIView   GenericAPIView
    -APIView
    	-执行流程:新的reqeust,三大认证,全局异常
        -重写了as_view,dispatch
        -类属性:parser_class,xxx
        
    -GenericAPIView---》继承了APIView----》以后,如果是跟数据库打交道,尽量用它
    	1 queryset:要序列化或反序列化的表模型数据
        2 serializer_class:使用的序列化类
        3 lookup_field :查询单条的路由分组分出来的字段名
        4 filter_backends:过滤类的配置(了解)
        5 pagination_class:分页类的配置(了解)

        # 方法
        1 get_queryset   :获取要序列化的对象
        2 get_object  :获取单个对象
        3 get_serializer :获取序列化类  ,跟它差不多的get_serializer_class,一般重写它,不调用它
        4 filter_queryset  :过滤有关系(了解)
        
        
    
    -补充,根据请求方式,定制序列化类
     def get_serializer(self, *args, **kwargs):
        if self.request.method=='GET':
            return 序列化单条的序列化类
        else:
            return 新增的序列化类
        
        
        

5个视图扩展类》》不是视图类》》必须配合GenericAPIView

每个类自己写一个方法,写的不是【请求方式,不是get,put...】的放,写的是list,destroy...
minin 混入,通过多继承来实现多个功能
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, DestroyModelMixin, RetrieveModelMixin,
    ListModelMixin
继承GenericAPIView+某个视图扩展类+请求方式的方法

今日内容

9个视图子类

2个视图基类

  1. APIView
  2. GenericAPIView

5个视图扩展类:需要配合GenericAPIView使用

  1. CreateModelMixin
  2. ListModelMixin
  3. RetrieveModelMixin
  4. UpdateModelMixin
  5. DestroyModelMixin

9个视图扩展类:不需要额外继承GenericAPIView

只需要继承9个中其中某个,就会有某个或某几个接口

  1. CreateAPIView
  2. ListAPIView
  3. RetrieveAPIView
  4. UpdateAPIView
  5. DestroyAPIView
  6. ListCreateAPIView
  7. RetrieveUpdateAPIView
  8. RetrieveDestroyAPIView
  9. RetrieveUpdateDestroyAPIView

image-20230206213511067

路由
urlpatterns = [
    path('books/', views.BookView.as_view()),
    path('books/<int:pk>/', views.BookView.as_view()),
]
视图类
class BookView(ListCreateAPIView):  # 查询所有,新增一个
    queryset = Book.objects.all()
    serializer_class = BookSerializer


# 新增一个,修改一个,删除一个
class BookDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

视图集

通过ModelViewSet编写5个接口

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

# 视图类
class BookView(ModelViewSet):  # 查询所有,新增一个
    queryset = Book.objects.all()
    serializer_class = BookSerializer

通过ReadOnlyModelViewSet编写两个接口

# 路由
urlpatterns = [
    path('api/v1/books/', views.BookView.as_view({'get': 'list'})),
    path('api/v1/books/<int:pk>/', views.BookView.as_view({'get': 'retrieve'})),

]

# 视图类
class BookView(ReadOnlyModelViewSet):  # 查询所有,新增一个
    queryset = Book.objects.all()
    serializer_class = BookSerializer

ViewSetMixin源码分析

请求来了,路由匹配成功》get请求匹配成功books,会执行views.BookView.as_view({'get': 'list', 'post': 'create'})()------>读as_view【这个as_view是ViewSetMixin的as_view】

@classonlymethod
    def as_view(cls, actions=None, **initkwargs):
        """
        Because of the way class based views create a closure around the
        instantiated view, we need to totally reimplement `.as_view`,
        and slightly modify the view function that is created and returned.
        """
        # The name and description initkwargs may be explicitly overridden for
        # certain route configurations. eg, names of extra actions.
        cls.name = None
        cls.description = None

        # The suffix initkwarg is reserved for displaying the viewset type.
        # This initkwarg should have no effect if the name is provided.
        # eg. 'List' or 'Instance'.
        cls.suffix = None

        # The detail initkwarg is reserved for introspecting the viewset type.
        cls.detail = None

        # Setting a basename allows a view to reverse its action urls. This
        # value is provided by the router through the initkwargs.
        cls.basename = None

        # actions must not be empty
        
        # 如果没有传actions,直接抛异常,路由写法变了后,as_view中不传字典,直接报错
        if not actions:
            raise TypeError("The `actions` argument must be provided when "
                            "calling `.as_view()` on a ViewSet. For example "
                            "`.as_view({'get': 'list'})`")

        # sanitize keyword arguments
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r" % (
                    cls.__name__, key))

        # name and suffix are mutually exclusive
        if 'name' in initkwargs and 'suffix' in initkwargs:
            raise TypeError("%s() received both `name` and `suffix`, which are "
                            "mutually exclusive arguments." % (cls.__name__))

        

        # take name and docstring from class
        update_wrapper(view, cls, updated=())

        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())

        # We need to set these on the view function, so that breadcrumb
        # generation can pick out these bits of information from a
        # resolved URL.
        view.cls = cls
        view.initkwargs = initkwargs
        view.actions = actions
        return csrf_exempt(view)

路由匹配成功执行views.BookView.as_view({'get': 'list', 'post': 'create'})()>本质执行ViewSetMixin>as_view>》内的view()–>

def view(request, *args, **kwargs):
            self = cls(**initkwargs)
	
            if 'get' in actions and 'head' not in actions:
                actions['head'] = actions['get']

            # We also store the mapping of request methods to actions,
            # so that we can later set the action attribute.
            # eg. `self.action = 'list'` on an incoming GET request.
            
            #actions 是传入的字典--->{'get': 'list', 'post': 'create'}
            self.action_map = actions

            # Bind methods to actions
            # This is the bit that's different to a standard view
            for method, action in actions.items():
                # 反射:去视图类中反射,action对应的方法,action第一次是list,去视图类中反射list方法
                # handler就是视图类中的list方法
                handler = getattr(self, action)
                # 在BookView视图类中添加了自己写的八大方法纯在的方法
                # 反射修改:把method:get请求方法,handler:list
                # 视图类的对象的get方法,变成了list
                setattr(self, method, handler)

            self.request = request
            self.args = args
            self.kwargs = kwargs

            # And continue as usual
            return self.dispatch(request, *args, **kwargs) #dispatch是APIView的
总结
  1. 只要继承ViewSetMixin的视图类,路由写法就变了(重写了as_view)
  2. 变成需要传入字典映射放{'get': 'list', 'post': 'create'}
    只要传入actions,以后访问get就是访问list,访问post就是方法问create
  3. 其他执行跟之前一样
  4. 以后视图类中的方法名,可以任意命名,只要在路由中做好映射即可

from rest_framework.viewsets包下的类

from rest_framework.viewsets下有这几个类
ModelViewSet:5个视图扩展类+GenericAPIView+ViewSetMinin
ReadOnlyModelVIewSet:两个视图扩展类+ViewSetMixin+GenericAPIView

ViewSetMixin:魔法类,重写了as_view,只要继承它,以后路由写法变成了映射方法
ViewSet:ViewSetMixin+APIView
GenericViewSet:ViewSetMixin+GenericAPIView

重点

以后,想继承APIView,但是想改变路由写法【视图类中方法名任意命名】,要继承ViewSet

以后,想要继承GenericAPIView,但是想改变路由写法【视图类中方法名任意命名】,要继承GenericViewSet

路由
path('api/v1/books/', views.BookView.as_view({'get': 'send_all'})),

视图函数
class BookView(GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    def send_all(self,request):
        return Response('返回')

路由系统

自动生成路由

drf由于继承ViewSetMixin类路由写法改变了
只要继承ViewSetMixin它默认对应的是,这几个

get--->list
get---->retrieve
put---->update
post---->create
delete---->destory
原生+drf,以后的路由写法,可能会有如下情况(三种情况)
path('books/', views.BookView.as_view()
path('books/', views.BookView.as_view({'get': 'list', 'post': 'create'}))
自动生成

drf提供了两个路由类,继承ModelViewSet后,路由可以自动生成

使用步骤:

第一步:导入路由类

第二步:实例化得到对象(两个类,一般使用SImpleRouter)

第三步:注册:router.register('books', views.BookView, 'books')

第四步:在urlpatterns中注册,两种方式

方法一

​ urlpatterns += router.urls

from rest_framework.routers import SimpleRouter, DefaultRouter
from app01 import views

router = SimpleRouter()
router.register('api/v1/books',views.BookView,'books')
urlpatterns = [
    path('api/v1/books/', views.BookView.as_view({'get': 'list', 'post': 'create'})),
    path('api/v1/books/<int:pk>/', views.BookView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]
urlpatterns +=router.urls
方法二

​ include:path('/api/v1/', include(router.urls)) 方式多一些

from rest_framework.routers import SimpleRouter, DefaultRouter
from app01 import views

router = SimpleRouter()
router.register('api/v1/books',views.BookView,'books')
urlpatterns = [
    path('', include(router.urls)),
]

底层实现:自动生成路由

本质就是自动做映射,能够自动生成前体是,视图类中要有5个方法的某一个或多个

get--->list
get---->retrieve
put---->update
post---->create
delete---->destory

ModelViewSet,ReadOnlyModelViewSet可以自动生成

9个视图子类+配合ViewSetMixin 才可以自动生成

GenericAPIView+5个视图扩展类+配合ViewSetMixin 才能生成

代码展示:

image

ps:实例化产生对象(router = SimpleRouter()),要不要传参数问题: 【结果就是相当于没有参数】

image

ps:路由注册传参数问题:

image

ps:写好路由之后发送地址的结果

image

总体代码实现:

action装饰器

action写在视图类中方法,才可以自动生成路由

使用步骤

1.写在视图类方法上

method指定请求方式,可以传多个['get', 'post']

detail:只能传True和False

​ True:带id的路径:books/2/send_all

​ False:不带id路由:books/send_all

url_path:生成send后路径的名字,默认以方法名命名

url_name:别名,反向解析使用,了解即可

from rest_framework.decorators import action
class BookView(GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    @action(methods=['get', 'post'], detail=False, url_name='send_all',
            url_path='send_all')  # 路由地址名 url_name='send_all',别名url_path='send_all'
    def send_all(self, request):
        return Response('返回')

以后看到的drf路由写法

后期,都是自动生成,一般不纯在urlpatterns加入路由了

补充:

  1. 不同请求方式可以使用不同序列化类
  2. 不同action使用不同序列化类
class SendView(GenericViewSet):
    queryset = None
    serializer_class = '序列化类'

    def get_serializer(self, *args, **kwargs):
        if self.action=='lqz':
            return '某个序列化类'
        else:
            return '另一个序列化列'
    @action(methods=['GET'], detail=True)
    def send_sms(self, request,pk):
        print(pk)
        # 手机号,从哪去,假设get请求,携带了参数
        phone = request.query_params.get('phone')
        print('发送成功,%s' % phone)
        return Response({'code': 100, 'msg': '发送成功'})

    @action(methods=['GET'], detail=True)
    def lqz(self,request):  # get
        # 序列化类
        pass

    @action(methods=['GET'], detail=True)
    def login(self,request):  # get
        # 序列化类
        pass
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet, GenericViewSet
from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.request import Request

class BookView(GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    @action(methods=['get', 'post'], detail=False, url_name='send_all',
            url_path='send_all')  # 路由地址名 url_name='send_all',别名url_path='send_all'
    def send_all(self, request):
        return Response('返回')

    @action(methods=['get'], detail=True)
    def aaa(self, request, pk):
        print(pk)
        return Response('aaa' + request.query_params.get('pp'))

    def get_serializer(self, *args, **kwargs):
        if self.action == 'aaa':
            return '一个'
        else:
            return '另一个'

微信图片_20230206214002

认证组件

访问某个接口,需要登录后才能访问

第一步:写个登录功能,用户表

User表

UserToken表:存储用户登录状态【这个表可以没有,如果没有,把字段直接写在User表上也可以】

登录接口
表模型

class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)



class UserToken(models.Model):  # 跟User是一对一
    token = models.CharField(max_length=32)
    user = models.OneToOneField(to='User', on_delete=models.CASCADE, null=True)
    # user :反向,表名小写,所有有user字段
# 视图类
####  登录接口  自动生成路由+由于登录功能,不用序列化,继承ViewSet
from .models import User, UserToken
import uuid


class UserView(ViewSet):
    @action(methods=['POST'], detail=False)
    def login(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username, password=password).first()
        if user:
            # 用户存在,登录成功
            # 生成一个随机字符串--uuid
            token = str(uuid.uuid4())  # 生成一个永不重复的随机字符串
            # 在userToken表中存储一下:1 从来没有登录过,插入一条,     2 登录过,修改记录
            # 如果有就修改,如果没有就新增  (if 自己写)
            # kwargs 传入的东西查找,能找到,使用defaults的更新,否则新增一条
            UserToken.objects.update_or_create(user=user, defaults={'token': token})
            return Response({'code': '100', 'msg': '登录成功', 'token': token})
        else:
            return Response({'code': '101', 'msg': '用户名或密码错误'})

练习

登录接口写完(if,我写的方式)

class UserView(GenericViewSet):
    @action(methods=['post', 'get'], detail=False)
    def login(self, request):
        user = User.objects.filter(username=request.data.get('username'), password=request.data.get('password')).first()
        # user.usertoken  # 如果不存在在会报错
        if user:
            token = str(uuid.uuid4())
            # 方法一
            # usertoken = UserToken.objects.filter(user=user).first()
            # if usertoken:
            #     usertoken.token = token
            #     usertoken.save()
            # else:
            #     UserToken.objects.create(token=token, user=user)

            # 方法二
            UserToken.objects.update_or_create(user=user,defaults={'token':token})

            request.session['token'] = token
            return Response({"code": 100, 'msg': '登录成功', 'token': token})
        else:
            return Response({'code': 101, 'msg': '用户名或密码错误'})

扩展

登录认证功能,没写,登录功能写完了
	-实现了图书5个接口
    -图书的查询所有和新增不需要登录访问
    -图书的查询一个,修改,删除,登录访问

url.py

from django.contrib import admin
from django.urls import path, include
from app01 import views

from rest_framework.routers import SimpleRouter, DefaultRouter
from app01 import views

router = SimpleRouter()
router.register('api/v1/books', views.BookView, 'books')
router.register('api/v1/user', views.UserView, 'user')

urlpatterns = [
    path('admin/', admin.site.urls),
path('', include(router.urls)),

]

views.py

from .models import User, UserToken
from rest_framework.decorators import action
import uuid
from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet


def authorLogin(func):
    def inner(request, *args, **kwargs):  # 如果使用 method_decorator装饰类函数就不需要写self参数,否则就需要写
    # def inner(self,request, *args, **kwargs):  # 如果使用 method_decorator装饰类函数就不需要写self参数,否则就需要写
        token = request.session.get('token')
        userToken = UserToken.objects.filter(token=token)
        if userToken:
            res = func(request, *args, **kwargs)
            # res = func(self,request, *args, **kwargs)
            return res
        else:
            return Response({'code': 101, 'msg': '未登录请先登录'})

    return inner


class UserView(GenericViewSet):
    @action(methods=['post', 'get'], detail=False)
    def login(self, request):
        user = User.objects.filter(username=request.data.get('username'), password=request.data.get('password')).first()
        # user.usertoken  # 如果不存在在会报错
        if user:
            token = str(uuid.uuid4())
            # 方法一
            # usertoken = UserToken.objects.filter(user=user).first()
            # if usertoken:
            #     usertoken.token = token
            #     usertoken.save()
            # else:
            #     UserToken.objects.create(token=token, user=user)

            # 方法二
            UserToken.objects.update_or_create(user=user,defaults={'token':token})

            request.session['token'] = token
            return Response({"code": 100, 'msg': '登录成功', 'token': token})
        else:
            return Response({'code': 101, 'msg': '用户名或密码错误'})


from django.utils.decorators import method_decorator


class BookView(ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    @method_decorator(authorLogin)  # 使用这个就不需要了
    # @authorLogin   # 使用这个就不行了
    def retrieve(self, request, *args, **kwargs):
        return super().retrieve(request, *args, **kwargs)

    @method_decorator(authorLogin)
    def update(self, request, *args, **kwargs):
        return super().update(request, *args, **kwargs)

    @method_decorator(authorLogin)
    def destroy(self, request, *args, **kwargs):
        return super().destroy(request, *args, **kwargs)
	# @method_decorator(authorLogin)
    # @action(['get'], detail=True)
    # def select_date(self, request, *args, **kwargs):
    #     return self.retrieve(request, *args, **kwargs)
    # 
    # @method_decorator(authorLogin)
    # @action(['PUT'], detail=True)
    # def update_date(self,request, *args, **kwargs):
    #     return self.update(request, *args, **kwargs)
    # 
    # @method_decorator(authorLogin)
    # @action(['DELETE'],detail=True)
    # def delete_date(self,request, *args, **kwarg):
    #     return self.destroy(request, *args, **kwarg)

serializer.py

from rest_framework import serializers
from .models import Book, Author, AuthorDetail, Publish


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['name', 'price', 'publish', 'authors', 'publish_detail', 'authors_detail']
        extra_kwargs = {
            'publish': {'write_only': True},
            'authors': {'write_only': True},
            'publish_detail': {'read_only': True},
            'authors_detail': {'read_only': True},
        }
    # 使用ModelViewSet视图类就不能使用下面的操作manytomany字段
    # authors = serializers.IntegerField(required=False, write_only=True)  # 主键值的用IntegerField字段

models.py

from django.db import models


# Create your models here.
class Book(models.Model):
    name = models.CharField(max_length=32, verbose_name='书名')
    price = models.CharField(max_length=32, verbose_name='价格')
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author', default=None)

    @property
    def publish_detail(self):
        return {'name': self.publish.name, 'addr': self.publish.addr}

    @property
    def authors_detail(self):
        return [{'name': obj.name, 'age': obj.age,
                 'authorDetail': {'phone': obj.authorDetail.phone, 'addr': obj.authorDetail.addr},
                 } for obj in self.authors.all()]


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


class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name='作者名字')
    age = models.CharField(max_length=32, verbose_name='作者年龄')
    authorDetail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    phone = models.CharField(max_length=32, verbose_name='手机号')
    addr = models.CharField(max_length=32, verbose_name='作者地址')


class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)


class UserToken(models.Model):
    token = models.CharField(max_length=64)
    user = models.OneToOneField(to='User', on_delete=models.CASCADE)

posted @ 2023-02-06 23:06  clever-cat  阅读(50)  评论(0编辑  收藏  举报