drf serialized data acquired Categories

  • Creating a route  
from django.urls import path,include
# 一级路由
urlpatterns = [
    
    path('pinmeimei/', include('pinmeimei.urls')),
]
  • Creating a Secondary Route
from django.urls import path
from . import views
#二级路由
urlpatterns = [
    path('category/',views.CategoryView.as_view() ),
    path('goods/',views.GoodsView.as_view() ),
]
  • Creating serializers.py convenient to write the serialized file
    •   Write serialized commodity classification in the py file
# Categories serialization 
class CategorySerializer (serializers.ModelSerializer): 

    class Meta -: 
        Model = models.Category   # specified table 

        # Fields = '__all__ is' # show all fields 
        Fields = ( ' ID ' , ' name ' )   # display can be specified field tuple or list
  • Categories Class
from rest_framework.views Import APIView
 from rest_framework.response Import the Response
 from . Import Models
 from serializers. Import * # commodity classification class in CategoryView (APIView):
     DEF GET (Self, Request): 
        category = models.Category.objects.filter (Status = . 1) .all ()    # obtaining valid data Categories 
        cate_date = CategorySerializer (category, MANY = True)   # of acquired data is serialized, a plurality of data plus = True MANY Print (cate_date)
         IF cate_date:   #



        If the present value of the status acquired status code returned, msg returned message, data according to the data returned restful style 
            return the Response ({
                 ' status ' : 200 is ,
                 ' MSG ' : '' ,
                 ' Data ' : cate_date.data 
            }) 
        return the Response ({
             ' Status ' : 201 ,
             ' MSG ' : ' network connection error, please try again later ' ,
             ' Data ' : '' 
        })
  •  test

Guess you like

Origin www.cnblogs.com/u-damowang1/p/12131057.html