码迷,mamicode.com
首页 > 其他好文 > 详细

drf 多表

时间:2019-04-20 00:05:09      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:create   elf   方法   org   一个   mod   field   数据   exclude   

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

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

一个 例子

from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r^admin/, admin.site.urls),
    url(rbooks/(\d+)/, views.BookHandle.as_view()),
    url(rbooks/, 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 render
from app01 import models
from rest_framework.views import APIView
from rest_framework import serializers
from 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 url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r^admin/, admin.site.urls),

    url(rbooks/$, views.BookHandle.as_view()),  # 不带参数的

    url(rbooks/(\d+)/, views.SBookHandle.as_view()), # 带参数的
]

 

drf 多表

标签:create   elf   方法   org   一个   mod   field   数据   exclude   

原文地址:https://www.cnblogs.com/zhangchen-sx/p/10739358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!