web front-end Vue + Django rest framework frame fresh electricity providers project combat video tutorial
web front-end Vue + Django rest framework frame fresh electricity providers project combat video tutorial to learn
1.drf preparation
1.django-rest-framework of official documents
https://www.django-rest-framework.org/
# Direct Baidu found djangorestframework official website is not open
2. Installation dependencies
As shown in FIG, Django restframework dependent module, and in addition coreapi django-guardian, has been installed in the front.
Open the terminal, the installation command
pip install django-guardian
pip install coreapi
3. rest_framework register settings in
url configuration when debugging api 4. Management will be used in the urls.py
from django.urls import path
from django.views.static import serve
from MxShop.settings import MEDIA_ROOT
from django.urls import include
import xadmin
from rest_framework.documentation import include_docs_urls
from goods.views import GoodsListView
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('media/<path:path>',serve,{'document_root':MEDIA_ROOT}),
path('ueditor/',include('DjangoUeditor.urls' )),
path ( 'docs /', include_docs_urls (title = " Mu Xuesheng fresh ")),
path('api-auth/', include('rest_framework.urls')),
path('goods/',GoodsListView.as_view(),name='goods-list'),
]
2. serialized commodity data
In New serializers.py file directory under goods
from rest_framework import serializers
from goods.models import Goods,GoodsCategory
class GoodsSerializer (serializers.Serializer): # Serializer embodiment serialized
name=serializers.CharField(required=True,max_length=100)
click_num=serializers.IntegerField(default=0)
goods_front_image=serializers.ImageField()
# For the post
def create(self, validated_data):
return Goods.objects.create(**validated_data)
class CategoryModelSerializer(serializers.ModelSerializer):
class Meta:
model=GoodsCategory
fields = "__ all __" # all the fields are serialized entire table
class GoodsModelSerializer(serializers.ModelSerializer):#ModelSerializer方式序列化
category = CategoryModelSerializer () # foreign key information embedding
class Meta:
model=Goods
# Fields = "__ all __" # all the fields are serialized entire table
fields = ( 'name', ' goods_front_image', 'category') # specific sequence of certain fields
3. View Package
1. Use APIView + Response implement the Product List Next View (CBV most wanted wording of native django)
views.py in
from .serializers import GoodsSerializer,GoodsModelSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Goods
from rest_framework import status
class GoodsListView1(APIView):
"""
List all goods,使用Serializer
"""
def get(self, request, format=None):
goods=Goods.objects.all()[:10]
goods_serializer = GoodsSerializer(goods, many=True)
return Response(goods_serializer.data)
def post(self,request,format=None):
serializer=GoodsSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
class GoodsListView2(APIView):
"""
List all goods,使用ModelSerializer
"""
def get(self, request, format=None):
goods=Goods.objects.all()[:10]
goods_serializer = GoodsModelSerializer(goods, many=True)
return Response(goods_serializer.data)
urls.py in
from django.contrib import admin
from django.urls import path
from django.views.static import serve
from MxShop.settings import MEDIA_ROOT
import xadmin
from goods.views import GoodsListView1,GoodsListView2
urlpatterns = [
path('admin/', admin.site.urls),
path('xadmin/', xadmin.site.urls),
path('media/<path:path>',serve,{'document_root':MEDIA_ROOT}),
path('ueditor/',include('DjangoUeditor.urls' )),
path('goods/',GoodsListView1.as_view(),name='goods-list'),
path('goods2/',GoodsListView2.as_view(),name='goods-list2')
]
2. mixins + generic view to achieve the Product List Next
from .serializers import GoodsSerializer
from .models import Goods
from rest_framework import mixins
from rest_framework import generics
class GoodsListView(mixins.ListModelMixin,generics.GenericAPIView):
"""
Product List Next
"""
queryset = Goods.objects.get_queryset().order_by('id')[:10]
serializer_class = GoodsSerializer
def get(self,request,*args,**kwargs):
return self.list(request,*args,**kwargs)
3. Use generics.ListAPIView view to achieve the Product List Next
from .serializers import GoodsSerializer
from .models import Goods
from rest_framework import generics
class GoodsListView(generics.ListAPIView):
"""
Product List Next
"""
queryset = Goods.objects.get_queryset().order_by('id')
serializer_class = GoodsSerializer
4. Paging
1. Global tab: Add the code in the settings, the list of all pages, will become pagination per page 10, it is clear that there are significant limitations
REST_FRAMEWORK={
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
2. Local custom tab: custom code in the view
from rest_framework.pagination import PageNumberPagination
class GoodsPagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
page_query_param = 'p'
max_page_size = 100
class GoodsListView(generics.ListAPIView):
"""
Product List Next
"""
queryset = Goods.objects.get_queryset().order_by('id')
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
5.viewsets
1. In the views of
from rest_framework import viewsets
class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
"""
Product List Next
"""
queryset = Goods.objects.get_queryset().order_by('id')
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
2. In the urls in
from goods.views import GoodsListViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'goods', GoodsListViewSet,base_name="goods")
urlpatterns = [ path('', include(router.urls)) ]