Python

Django前后端分离实践之DRF--07

2018-10-21  本文已影响23人  f050d162bcc1

一、超链接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)
选区_016

5. 增加新的路由

    url(r'^books/$',views.BookList.as_view()),
    url(r'^books/(?P<pk>[0-9]+)/$',views.BookDetail.as_view())
选区_017 选区_018

6. 增加几条数据

选区_019 选区_020

7. 通过外键重写显示字段转化为字符串(StringRelatedField)

publisher = serializers.StringRelatedField(source='publisher.name')
选区_021 选区_022

8.设置超链接

选区_023 选区_024 选区_025 选区_026

二、浏览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)
        }
    )
选区_030

3. 在app下面单独创建一个urls

选区_027
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')

]


选区_028 选区_029 选区_031

三、分页

设置分页样式

'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
选区_032

[图片上传失败...(image-f97ab3-1540133351593)]

选区_054

分页_拓展阅读

上一篇下一篇

猜你喜欢

热点阅读