一 生成hypermedialink(极少数)
组件
class BooksSerializer(serializers.ModelSerializer):
name = serializers.CharField()
class Meta:
model = models.Book
fields = '__all__'
# 生成链接,直接查看出版社详情
publish = serializers.HyperlinkedIdentityField(view_name='ttt', lookup_field='publish_id',
lookup_url_kwarg='pk')
authors = serializers.SerializerMethodField()
def get_authors(self, obj):
ret = obj.authors.all()
ss = AuthorSerializer(ret, many=True)
return ss.data
view
class Books(APIView):
def get(self, request, *args, **kwargs):
ret = models.Book.objects.all()
book_ser = BooksSerializer(ret, many=True,context={'request': request})
# 注意: 要在有返回链接的函数中要加 context={'request': request}
print(book_ser)
return JsonResponse(book_ser.data, safe=False)
url
url(r'^publish/(?P<pk>\d+)$', views.Publish.as_view(), name='ttt'),
返回到前端的数据