django rest_framework의 APIView

19783 단어
models.py
from django.db import models

# Create your models here.


class UserInfo(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)

class UserToken(models.Model):
    token = models.CharField(max_length=128)
    userinfo = models.OneToOneField(to="UserInfo")


class Publisher(models.Model):
    name = models.CharField(max_length=64)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Book(models.Model):
    title=models.CharField(max_length=64)
    price = models.IntegerField()
    pub_date = models.DateField()
    publisher=models.ForeignKey(to='Publisher')
    authors = models.ManyToManyField(to="Author")
    def __str__(self):
        return self.title

class Author(models.Model):
    name = models.CharField(max_length=48)
    age = models.IntegerField(default=2)
    def __str__(self):
        return self.name

views.py
from django.shortcuts import render

from app01 import models
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView

class PublisherModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Publisher
        fields = "__all__"

class BookModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = "__all__"

        #       
        #      
    publisher = serializers.HyperlinkedIdentityField(
        view_name="publisher_detail",  # url     url       name="publisher_detail"
        lookup_field="publisher_id", #        
        lookup_url_kwarg="pk",
    )
    #      ,       ,          name     ,            publisher      post     create  
    # publisher = serializers.CharField(source="publisher.name")#            
    # authors = serializers.CharField(source="authors.all") #      
    #                ,      
    # authors =serializers.SerializerMethodField() ##     
    # def get_authors(self,obj):
    #     temp = []
    #     for obj in obj.authors.all():
    #         temp.append(obj.name)
    #         print(temp)
    #     return temp
    ##              post     create  ,            create  
    def create(self,validated_data):
        print("validated_data",validated_data)
        book = models.Book.objects.create(title=validated_data["title"],price=validated_data["price"],pub_date=validated_data["pub_date"],publisher_id=validated_data["publisher"]["pk"])
        book.authors.add(*validated_data["authors"])
        return book

class AuthorModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Author
        fields = "__all__"
class PublisherView(APIView):

    #       
    def get(self,request):

        pub_list = models.Publisher.objects.all()
        pub_ser = PublisherModelSerializer(pub_list,many=True) #       querset  ,   many=true,       ,   
        return Response(pub_ser.data)
    #     
    def post(self,request):
        print(request._request.body)
        print(request._request.POST)
        print("==========")
        print(request.data)


        pub_ser = PublisherModelSerializer(data=request.data)
        if pub_ser.is_valid():
            print(pub_ser.validated_data)
            pub_ser.save()
            return Response(pub_ser.data)
        else:
            return Response(pub_ser.errors)

class PublisherDetailView(APIView):
    #       
    def get(self,request,pk):
        pub_obj = models.Publisher.objects.filter(pk=pk).first()
        pub_ser = PublisherModelSerializer(pub_obj)
        return Response(pub_ser.data)
    #             id    ,        ,    
    def put(self,request,pk):
        pub_obj = models.Publisher.objects.filter(pk=pk).first()
        pub_ser = PublisherModelSerializer(pub_obj,data=request.data)
        if pub_ser.is_valid():
            pub_ser.save()
            return Response(pub_ser.data)
        else:
            return Response(pub_ser.errors)
    #       
    def delete(self,request,pk):
        models.Publisher.objects.filter(pk=pk).delete()
        return Response()
class BookView(APIView):

    def get(self,request):
        #http://127.0.0.1:8000/books/?a=1&b=2
        print(request._request.body) #b''  request._request.body         ,GET       
        print(request._request.GET)  ##    url    

        book_list = models.Book.objects.all()
        book_ser = BookModelSerializer(book_list,many=True,context={"request": request})  #          context={"request":request}
        return Response(book_ser.data)

    def post(self,request):
        print(request.data)
        book_ser = BookModelSerializer(data=request.data)
        print(book_ser)
        print("========")
        print(book_ser.publisher)
        if book_ser.is_valid():
            print(book_ser.validated_data)
            book_ser.save()
            return Response(book_ser.data)
        else:
            return Response(book_ser.errors)

class BookDetailView(APIView):

    def get(self,request,pk):
        book_obj = models.Book.objects.filter(pk=pk).first()
        book_ser = BookModelSerializer(book_obj,context={"request":request}) #          context={"request":request}
        return Response(book_ser.data)

    def put(self,request,pk):
        book_obj = models.Book.objects.filter(pk=pk).first()
        book_ser = BookModelSerializer(book_obj,data=request.data)
        if book_ser.is_valid():
            book_ser.save()
            return Response(book_ser.data)
        else:
            return Response(book_ser.errors)

    def delete(self,request,pk):
        models.Book.objects.filter(pk=pk).delete()
        return Response()

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

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

    url(r'^publisher/$', views.PublisherView.as_view()),
    # url(r'^publisher/(\d+)/$', views.PublisherDetailView.as_view()), #     
    url(r'^publisher/(?P\d+)/', views.PublisherDetailView.as_view(), name="publisher_detail"), #    
    #    PublisherDetailView    ,  as_view()     view,      APIView   (View) as_view()  view,
    #view       dispatch     ,dispatch    view     ,APIView  dispatch  ,  APIView  dispatch
    #dispatch  handle  getattr    PublisherDetailView  get.post,put,delete  


    url(r'^books/$', views.BookView.as_view()),
    url(r'^books/(?P\d+)/$', views.BookDetailView.as_view()),
]

프로젝트 주소:https://github.com/CH-chen/APIView_demo
전재 대상:https://www.cnblogs.com/chvv/p/10047082.html

좋은 웹페이지 즐겨찾기