序列化器设计
from rest_framework import serializers
from .models import Poem
# Poem为数据表名
class PoemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Poem
fields = ['url','title','content','price']
视图函数
from rest_framework import viewsets
from .models import Poem
from .serializers import PoemSerializer
class BookNewAPI(viewsets.ModelViewSet):
queryset = Poem.objects.all()
serializer_class = PoemSerializer
urls
from rest_framework import routers
from .apis import BookNewAPI
route = routers.DefaultRouter()
route.register(r'books',BookNewAPI)
添加进项目urls中
from myapp.urls_api import route
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^myappnew/',include(route.urls)),
]
这篇博客只是学习序列化器的使用。因此其中原理没有了解。只是使用
restful不只是一种设计模式。是一种设计思想,从资源的角度观察整个网路。使用request response,models等。使得设计变得简明,清晰。