django rest_framework의 APIView
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.