超链接API:Hyperlinked
它指的是当你返回的结果中有一对多或多对多时,这时候,服务器会返回一条url,你点击这个url就会直接看到具体的信息,
比如对于单个book对象来说,他返回的hyperlinked,点进去就会看到publish的id,title,email等信息
urls.py:
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^books/$', BookView.as_view()), url(r'^publishes/$', PublishView.as_view()), url(r'^books/(?P<pk>d+)/$',BookdetailView.as_view(),name="books"), url(r'^publishes/(?P<pk>d+)/$',PublishdetailView.as_view(),name="publishes") ]
serializers_base.py:
from rest_framework import serializers from api_demo.models import * class Bookserializers(serializers.ModelSerializer): # 导入ModelSerializer这个类 publish = serializers.HyperlinkedIdentityField( view_name='publishes', # publish具体对象对应的url别名 lookup_field="publish_id", # 该字段在表book中的字段名 lookup_url_kwarg="pk") # publish具体对象对应的url中参数的名字 class Meta: model = Book fields = "__all__" # 对多对字段默认是主键值 depth = 1
注意
这里你也要设计url.和序列化publish,否则超链接不会成功,代码因为重复我没有写
出现问题:
`HyperlinkedIdentityField` requires the request in the serializer context.Add `context={'request': request}` when instantiating the serializer.
这里要求我们在所有调用Bookserializers类进行序列化对象时都要添加上`context={'request': request},否则就会报上边的错误
class BookView(APIView): def get(self,request,*args,**kwargs): booklist=Book.objects.all() temp=Bookserializers(booklist,many=True,context = {'request': request})# 序列化操作,如果传入的是多个值,many=True,默认False return Response(temp.data) #发送其中的data就可以 def post(self,request,*args,**kwargs): """ 添加函数 :param request: :param args: :param kwargs: :return: """ data=request.data #postman发过来的json,后端要用request.data来接收 bs=Bookserializers(data=data,context = {'request': request}) #这里包括了反序列化,生成对象,但是没有保存到数据库中 if bs.is_valid():#校验数据 bs.save() return Response(bs.data) else: return Response(bs.errors) #对book表中的单个数据进行查看,删除,编辑 class BookdetailView(APIView): def get(self,request,book_id,*args,**kwargs): """ 对单个对象查 :param request: :param book_id: :param args: :param kwargs: :return: """ book_obj=Book.objects.filter(pk=book_id).first() temp=Bookserializers(book_obj,context = {'request': request}) return Response(temp.data) def put(self,request,book_id,*args,**kwargs): """ 对单个对象编辑 :param request: :param book_id: :param args: :param kwargs: :return: """ book_obj=Book.objects.filter(pk=book_id).first() temp=Bookserializers(data=request.data,instance=book_obj,context = {'request': request}) if temp.is_valid(): temp.save() return Response(temp.data) else: return Response(temp.errors)