博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
drf 多表
阅读量:6690 次
发布时间:2019-06-25

本文共 5273 字,大约阅读时间需要 17 分钟。

https://www.django-rest-framework.org/  官方站

https://www.django-rest-framework.org/tutorial/quickstart/#serializers    -- 序列化

一个 例子

from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'books/(\d+)/', views.BookHandle.as_view()),    url(r'books/', views.BookHandle.as_view()),]
class BookHandle(APIView):    # 获取所有书籍    def get(self, request,id=None):        if id:            books_obj_list = models.Book.objects.filter(id=id)        else:            books_obj_list = models.Book.objects.all()        book_se = BookSerializer(books_obj_list, many=True)  # 要点        return Response(book_se.data)

查询全部和带参数的查询 -- 

from django.shortcuts import renderfrom app01 import modelsfrom rest_framework.views import APIViewfrom rest_framework import serializersfrom rest_framework.response import Response   # 响应class BookSerializer(serializers.ModelSerializer):    class Meta:        model = models.Book        fields = '__all__'  # exclude = ('user',) 排除某些字段的方法    fields=['','']列表         class BookHandle(APIView):    # 获取所有书籍    def get(self, request,id=None):        if id:            books_obj_list = models.Book.objects.filter(nid=id)        else:            books_obj_list = models.Book.objects.all()        book_se = BookSerializer(books_obj_list, many=True)  # 要点        return Response(book_se.data)    def post(self, request):        cs = BookSerializer(data=request.data,many=False)        if cs.is_valid():            cs.save()  # create 新建            return Response(cs.data)        else:            return Response(cs.errors)class SBookHandle(APIView):    # 更新数据    def put(self,request,id):        old_obj = models.Book.objects.filter(pk=id).first()  # querySet        cs = BookSerializer(data=request.data,many=False,instance=old_obj)        if cs.is_valid():            cs.save()   # 更新 update            return Response(cs.data)        else:            return Response(cs.errors)    def delete(self,request,id):        models.Book.objects.filter(pk=id).delete()  # 删除        return Response('')    def get(self,request,id):        books_obj_list = models.Book.objects.get(pk=id)  # model 类型        book_se = BookSerializer(books_obj_list,many=False)        return Response(book_se.data)
from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'books/$', views.BookHandle.as_view()),  # 不带参数的    url(r'books/(\d+)/', views.SBookHandle.as_view()), # 带参数的]

 

-- views.py --# 进阶版from rest_framework.mixins import CreateModelMixin,UpdateModelMixin,DestroyModelMixin,ListModelMixin,RetrieveModelMixinfrom rest_framework import genericsclass PublishHandle(ListModelMixin,CreateModelMixin,generics.GenericAPIView):    queryset = models.Publish.objects.all()    serializer_class = PublishSerializer    def get(self, request):        return self.list(request)    def post(self, request):        return self.create(request)class SPublishHandle(UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin, generics.GenericAPIView):    queryset = models.Publish.objects.all()    serializer_class = PublishSerializer    def put(self, request,*args,**kwargs):        return self.update(request,*args,**kwargs)  # update    def delete(self, request,*args,**kwargs):        return self.destroy(request,*args,**kwargs)  # destroy    def get(self, request,*args,**kwargs):        return self.retrieve(request,*args,**kwargs)  # retrieve# 极简版# class AuthorHandle(generics.ListCreateAPIView):  # 查询创建二合一#     queryset = models.Author.objects.all()#     serializer_class = AuthorSerializer# ## class SAuthorHandle(generics.RetrieveUpdateDestroyAPIView):  # 查单 更新 删除  三合一#     queryset = models.Author.objects.all()#     serializer_class = AuthorSerializer#终极版from rest_framework.viewsets import ModelViewSetclass SAuthorHandle(ModelViewSet):  # 全合一    queryset = models.Author.objects.all()    serializer_class = AuthorSerializer-- all_serializer.py --from app01 import modelsfrom rest_framework import serializersfrom rest_framework.response import Response   # 响应from rest_framework.views import APIViewclass BookSerializer(serializers.ModelSerializer):   # create     update    class Meta:        model = models.Book        fields = '__all__'class PublishSerializer(serializers.ModelSerializer):    class Meta:        model = models.Publish        fields = '__all__'class AuthorSerializer(serializers.ModelSerializer):    class Meta:        model = models.Author        fields = '__all__'-- urls.py --from django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [    url(r'^admin/', admin.site.urls),    url(r'books/$', views.BookHandle.as_view()),  # 不带参数的    url(r'books/(\d+)/', views.SBookHandle.as_view()),  # 带参数的    url(r'publishs/$', views.PublishHandle.as_view()),  # 不带参数的    url(r'publishs/(?P
\d+)/', views.SPublishHandle.as_view()), # 不带参数的 url(r'authors/$', views.SAuthorHandle.as_view({
'get':'list','post':'create'})), # 不带参数的 url(r'authors/(?P
\d+)/', views.SAuthorHandle.as_view({
'get':'retrieve','put':'update','delete':'destroy'})), # 不带参数的]

 

转载于:https://www.cnblogs.com/zhangchen-sx/p/10739358.html

你可能感兴趣的文章
代码实现从某个表中查询数据插入到另一个表中
查看>>
提高代码质量-工具篇
查看>>
require() 源码解读
查看>>
kvm虚拟化学习笔记(十六)之kvm虚拟化存储池配置
查看>>
★Kali信息收集~ 5.The Harvester:邮箱挖掘器
查看>>
普通web项目转化为maven web项目
查看>>
android 内部文件读取
查看>>
磁带机Media is unrecognized
查看>>
DH密钥交换非对称加密
查看>>
程序员的量化交易之路(19)--Cointrader之Bar实体(7)
查看>>
[Android]getevent,sendevent,input命令的使用
查看>>
开始转移精力,研究BI方向
查看>>
Android配置----adb工具的使用
查看>>
TNS-12502: TNS:listener received no CONNECT_DATA from client
查看>>
【DB2 学习】在复原过程中重定义表空间
查看>>
【mongodb系统学习之八】mongodb shell常用操作
查看>>
教你如何封装异步网络连接NSURLConnection实现带有百分比的下载
查看>>
【RAC】单节点 重启 报ORA-1105 ORA-01606
查看>>
Java IO: 流
查看>>
剑指offer系列之三:在二维数组中查找元素
查看>>