其他分享
首页 > 其他分享> > django rest framework快速使用

django rest framework快速使用

作者:互联网

一、安装相关的依赖

$ pip install djangorestframework
$ pip install markdown       # Markdown support for the browsable API.
$ pip install django-filter  # Filtering support

二、将rest_framework添加到INSTALLED_APPS中

setting.py

INSTALLED_APPS = [
    ...
    'rest_framework',
]

三、基础例子

  1. 创建一个django项目并创建book app

    $ python djang-admin createproject myapp
    $ python manage.py startapp book
    
  2. 新建model

    book/models.py

    from django.db import models
    class Book(models.Model):
        title = models.CharField(max_length=32, verbose_name='书籍名称')
        price = models.IntegerField(verbose_name="价格")
        pub_date = models.DateField(verbose_name="出版日期")
    
  3. 创建Book序列化器和Book view

    book/views.py

    # 序列化器
    class BookViewSerializer(serializers.Serializer):
        title = serializers.CharField(max_length=32)
        price = serializers.IntegerField()
         # 自定义映射参数中的字段和model字段
        date = serializers.DateField(source='pub_date')
    
        def create(self, validated_data):
            saved_book = Book.objects.create(**validated_data)
            return saved_book
    
        def update(self, instance, validated_data):
            Book.objects.filter(pk=instance.pk).update(**validated_data)
            return Book.objects.get(pk=instance.pk)
    
    # 视图
    class BookView(APIView):
    
        def get(self, request):
            book_list = Book.objects.all()
            b = BookViewSerializer(instance=book_list, many=True)
            return Response(b.data)
    
        def post(self, request):
            data = request.data
            # 反序列化
            sers = BookViewSerializer(data=data)
            # 校验字段
            if sers.is_valid():
                valid_data = sers.validated_data
                sers.save()
                # print(saved_book)
                return Response(sers.data)
            else:
                return Response(sers.errors)
    
    # 视图
    class BookDetailView(APIView):
        def get(self, request, id):
            book = Book.objects.get(pk=id)
            res = BookViewSerializer(instance=book)
            return Response(res.data)
    
        def put(self, request, id):
            data = request.data
            query_data = Book.objects.get(pk=id)
            sers = BookViewSerializer(instance=query_data, data=data)
            if sers.is_valid():
                print(sers.validated_data)
                sers.save()
                return Response()
            else:
                return Response(sers.errors)
    
        def delete(self, request, id):
            Book.objects.filter(pk=id).delete()
            return Response()
    
    
  4. 配置路由

    book/urls.py

    from django.urls import path, re_path
    
    from . import views
    urlpatterns = [
        path('book/', views.BookView.as_view()),
        re_path('book/(\d+)', views.BookDetailView.as_view()),
    ]
    
  5. 将应用路由添加到项目路由中

    myapp/urls.py

    urlpatterns = [
        ...
        path('book/', include('book.urls'))
    ]
    
  6. 安装app

    myapp/settings.py

    INSTALLED_APPS = [
        ...
        'rest_framework',
      	'book',
    ]
    
  7. 访问路由

    列表:curl http://server/book/book/ get
    详情:curl http://server/book/book/1 get
    添加:curl http://server/book/book/ post
    更新:curl http://server/book/book/1 put
    删除:curl http://server/book/book/1 delete
    

四、Django rest framework高度封装例子

在步骤三中的项目为基础,model无变化

  1. Views.py修改

    book/views.py

    from rest_framework.viewsets import ModelViewSet
    from rest_framework import serializers
    # 序列化器
    class BookViewSerializer(serializers.ModelSerializer):
        date = serializers.CharField(source='pub_date') # 自定义映射参数中的字段和model字段
        class Meta:
            model = Book
            exclude = ['pub_date']
    # 视图        
    class BookView(ModelViewSet):
        queryset = Author.objects.all()
        serializer_class = AuthorSerializer
    
  2. urls.py修改

    from rest_framework import routers
    router = routers.DefaultRouter()
    
    router.register('book', views.BookView)
    
    urlpatterns = [
        ...
    ]
    urlpatterns += router.urls
    

    router.register('book', views.BookView)将会生成和步骤三.4一样的路由

    path('book/', views.BookView.as_view()),
    re_path('book/(\d+)', views.BookDetailView.as_view()),
    

    后面的访问和步骤三一致。

标签:return,sers,py,rest,django,framework,Book,data,book
来源: https://www.cnblogs.com/yourblog/p/16609150.html