rest_framework中有五大基础接口:get_list(获得多条数据),get_one(获得一条数据),post_one(添加一条数据),put_one(修改一条数据),delete_one(删除一条数据)
五大接口基础实现
from rest_framework
.views
import APIView
from rest_framework
.response
import Response
from app
import models
, objson
class Books(APIView
):
def get(self
, request
, *args
, **kwargs
):
book_list
= models
.Book
.objects
.all()
book_data
= objson
.BookJson
(book_list
, many
=True).data
return Response
({
'status': 0,
'msg': 'ok',
'results': book_data
})
def post(self
, request
, *args
, **kwargs
):
book_json
= objson
.BookJson
(data
=request
.data
)
if book_json
.is_valid
():
book_json
.save
()
return Response
({
'status': 0,
'msg': 'ok',
'results': book_json
.data
})
return Response
({
'status': 1,
'msg': book_json
.errors
,
})
class Book(APIView
):
def get(self
, request
, pk
, *args
, **kwargs
):
book
= models
.Book
.objects
.filter(pk
=pk
).first
()
book_data
= objson
.BookJson
(book
).data
return Response
({
'status': 0,
'msg': 'ok',
'results': book_data
})
def put(self
, request
, pk
, *args
, **kwargs
):
book
= models
.Book
.objects
.filter(pk
=pk
).first
()
book_json
= objson
.BookJson
(data
=request
.data
, instance
=book
)
if book_json
.is_valid
():
book_json
.save
()
return Response
({
'status': 0,
'msg': 'ok',
'results': book_json
.data
})
return Response
({
'status': 1,
'msg': book_json
.errors
,
})
def delete(self
, request
, pk
, *args
, **kwargs
):
deleted
, _
= models
.Book
.objects
.filter(pk
=pk
).delete
()
if deleted
!= 0:
return Response
({
'status': 2,
'msg': 'delete success',
})
return Response
({
'status': 1,
'msg': 'delete failed',
})
视图模块:ModelViewSet,实现五大接口
from rest_framework
.viewsets
import ModelViewSet
from app
import models
, objson
class Books(ModelViewSet
):
queryset
= models
.Book
.objects
serializer_class
= objson
.BookJson
class Book(ModelViewSet
):
queryset
= models
.Book
.objects
serializer_class
= objson
.BookJson
lookup_field
= 'pk'
from app
import views
urlpatterns
= [
url
(r
'^books/', views
.Books
.as_view
({'get': 'list', 'post': 'create'})),
url
(r
'^book/(?P<id>\d+)/', views
.Book
.as_view
({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),
]
项目开发中的具体使用,可以再原有的五大接口上进行无限的扩展或者直接重写五大接口
from rest_framework
.viewsets
import ModelViewSet
from rest_framework
.response
import Response
from app
import models
, objson
class BookView(ModelViewSet
):
def get_list(self
, request
, *args
, **kwargs
):
book_list
= models
.Book
.objects
.all()
book_data
= objson
.BookJson
(book_list
, many
=True).data
return Response
({
'status': 0,
'msg': 'ok',
'results': book_data
})
from app
import views
urlpatterns
= [
url
(r
'^books/', views
.BookView
.as_view
({'get': 'get_list'})),
]
路由模块
from app
import views
urlpatterns
= [
url
(r
'^books/', views
.Books
.as_view
()),
]
urlpatterns
= [
url
(r
'^books/', views
.BookView
.as_view
({'get': 'get_list'})),
]
转载请注明原文地址: https://yun.8miu.com/read-19468.html