1. 程式人生 > >使用Restframework+django_filters快速實現Django的API

使用Restframework+django_filters快速實現Django的API

環境:

pip install restframework=3.4.6

pip install django_filter

project->settings.py

  ​
  INSTALLED_APPS = [
      'django.contrib.admin',
      'django.contrib.auth',
      'django.contrib.contenttypes',
      'django.contrib.sessions',
      'django.contrib.messages',
      'django.contrib.staticfiles',
      'market',
      'rest_framework', # 註冊app
  ]
  ​
  # 修改配置  rest_framework
  REST_FRAMEWORK = {
      # 將 restframework 預設的使用者認證取消
      'DEFAULT_AUTHENTICATION_CLASS': (),
      # 篩選過濾資料
      'DEFAULT_FILTER_BACKENDS':(
          'rest_framework.filters.DjangoFilterBackend',
          'rest_framework.filters.SearchFilter',
      ),
  }

app->urls.py

  ​
  ​
  from django.conf.urls import url
  from rest_framework.routers import SimpleRouter
  ​
  from market import views
  ​
  ​
  router = SimpleRouter()
  router.register(r'^goods', views.GoodsApi)
  ​
  urlpatterns = [
      url(r'^index/', views.index, name='index'),
  ]
  urlpatterns += router.urls
  ​

app->views.py

  
  class GoodsApi(mixins.ListModelMixin,  # get
                 mixins.CreateModelMixin,  # post
                 mixins.RetrieveModelMixin,  # 單個查詢
                 mixins.UpdateModelMixin,  # 修改 put 全部  patch 部分
                 mixins.DestroyModelMixin,  # 刪除 delete
                 viewsets.GenericViewSet):
      """商品 API """
      # 從資料庫中獲取的資料
      queryset = Goods.objects.filter(good_id__lt=200)
      # 資料序列化器, 將查詢的資料進行處理,返回格式良好的資料
      serializer_class = GoodSerializer
      # 自定義的過濾器,對資料進行篩選
      filter_class = GoodsFilter

utils->serializers.py

  ​
  from rest_framework import serializers
  ​
  from market.models import Goods
  ​
  ​
  class GoodSerializer(serializers.ModelSerializer):
      """自定義商品序列化器"""
      class Meta:
          model = Goods
  ​
      # 對獲取到的資料進行資料格式化
      def to_representation(self, instance):
          data = super().to_representation(instance)
          category_id= data.pop('category')
          data['brand_id'] = brand_id
          return data
  ​

utils->filters.py

  
  ​
  import django_filters
  from rest_framework import filters
  ​
  from market.models import Goods, GoodsBrand, GoodsCategory
  ​
  ​
  class GoodsFilter(filters.FilterSet):
      """用於商品查詢的過濾器"""
      class Meta:
          model = Goods
          # 用於查詢的欄位
          fields = '__all__'
  ​
      # 定義查詢的方法 contains:模糊查詢; gte:大於等於; lte:小於等於
      # url : /market/goods/?good_id_lte=160&  新增其他條件
      good_id = django_filters.CharFilter('good_id', lookup_expr='exact')
      good_name = django_filters.CharFilter('good_name', lookup_expr='icontains')
      good_category_id = django_filters.CharFilter('category_id', lookup_expr='exact')
      good_brand_id = django_filters.CharFilter('brand_id', lookup_expr='exact')
      good_amount_lte = django_filters.CharFilter("real_amount", lookup_expr='lte')
      good_amount_gte = django_filters.CharFilter("real_amount", lookup_expr='gte')
  ​

介面訪問的方法說明

GET 請求

  
  ​
  GET  /market/goods/? + params

params

  
  ​
  good_id=<id>  # 獲取 id 的商品
  good_name=<name>  # 模糊查詢 獲取該名字的商品
  good_category_id=<id>  # 商品分類id
  good_brand_id=<id>  # 商品品牌 id
  good_amount_lte=<price>  # 獲取商品價格小於 price 的商品
  good_amount_gte=<price>  # 獲取商品價格大於 price 的商品
  ​
  # 可以多個條件一起查詢
  good_amount_lte=<price>&good_amount_gte=<price>