带超链接的模型的序列化
1,配置
我们需要添加我们的新snippets应用和rest_framework应用INSTALLED_APPS。让我们编辑tutorial/settings.py文件:
INSTALLED_APPS = (
...
'rest_framework',
)
2,创建一个可使用的模型
3,创建一个Serializer类。
from rest_framework import serializers
from App.models import User, Group
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
3,在views里写视图函数(类基础函数)
from django.contrib.auth.models import User, Group
from django.views.generic import ListView, DetailView
from rest_framework import viewsets
from App.models import Book
from App.serializers import UserSerializer, GroupSerializer
class HelloListView(ListView):
template_name = 'hello_list.html'
queryset = Book.objects.all()
class BookDetail(DetailView):
template_name = 'book_detail.html'
queryset = Book.objects.all()
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
4,urls的配置:
利用序列化创建url的方式
from App.views import UserViewSet, GroupViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('users', UserViewSet)
router.register('groups', GroupViewSet)
在系统里的url配置:
from App.urls import router
path('app/', include(router.urls)),