一、超链接API
目前我们的API中的关系是用主键表示的。我们将通过使用超链接来提高我们API的内部联系。
1. 新建一张表(模型类)
class Book(models.Model):
title = models.CharField(max_length=32, verbose_name='书名')
publisher = models.ForeignKey('Publisher')
def __str__(self):
return self.title
class Meta:
verbose_name = '书'
verbose_name_plural = verbose_name
2. 生成迁移文件和执行迁移
3. 创建书的序列化
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = (
'id',
'title',
'publisher'
)
4. 编写Book相关视图
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = serializers.BookSerializer
permission_classes = (permissions.IsAuthenticated,)
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = serializers.BookSerializer
permission_classes = (permissions.IsAuthenticated)
5. 增加新的路由
url(r'^books/$',views.BookList.as_view()),
url(r'^books/(?P<pk>[0-9]+)/$',views.BookDetail.as_view())
- 没数据
6. 增加几条数据
7. 通过外键重写显示字段转化为字符串(StringRelatedField)
publisher = serializers.StringRelatedField(source='publisher.name')
8.设置超链接
- 解决报错
二、浏览API
1. 导入模块
from rest_framework.reverse import reverse
2. 编写视图函数
@api_view(['GET'])
def api_root(request, format=None):
return Response(
{
'publishers': reverse('publisher-list', request=request, format=format),
'books': reverse('books_list', request=request, format=format)
}
)
3. 在app下面单独创建一个urls
from django.conf.urls import url, include
from app01 import views
urlpatterns = [
url(r'^publishers/$', views.PublisherList.as_view(), name='publisher-list'),
url(r'^publishers/(?P<pk>[0-9]+)/$', views.PublisherDetail.as_view(), name='publisher-detail'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest-framework')),
url(r'^books/$', views.BookList.as_view(), name='books_list'),
url(r'^books/(?P<pk>[0-9]+)/$', views.BookDetail.as_view(), name='books-detail')
]
- 刷新浏览器,展示所有api
三、分页
设置分页样式
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
[图片上传失败...(image-f97ab3-1540133351593)]