objson.py
from rest_framework import serializers
from app import models
class BookJson ( serializers. ModelSerializer) :
class Meta :
model = models. Book
fields = '__all__'
views.py
from rest_framework. viewsets import ModelViewSet
from rest_framework. response import Response
from app import models. objson
class BookView ( ModelViewSet) :
queryset = models. Book. objects. all ( )
serializer_class = objson. BookJson
lookup_field = 'pk'
def get_book_by_id ( self, request, id , * args, ** kwargs)
book = models. Book. objects. filter ( pk= id ) . first( )
book_data = objson. BookJson( book) . data
return Response(
{ 'status' : 0 ,
'msg' : 'ok' ,
'result' : book_data
}
)
urls.py
from app import views
urlpatterns = [
url( r'^books/' , views. BookView. as_view( { 'get' : 'list' , 'post' , 'create' } ) ) ,
url( r'^book/(?P<pk>\d+)/' , views. BookView. as_view( { 'get' : 'retrieve' , 'put' : 'update' , 'delete' : 'destroy' } ) ) ,
url( r'book/(?P<id>\d+)/' , views. Bookview. as_view( { 'get' : 'get_book_by_id' } ) )
]