Win10升级本地Django版本,以及DRF框架的安装使用
-
windows升级django版本
C:UsersAdministrator>pip install --upgrade Django==2.2.14 Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple Collecting Django==2.2.14 Downloading
-
django restframework 框架的安装
pip install djangorestframework
-
在settings.py中配置drf
# 在app中进行注册 INSTALLED_APPS = [ ... 'rest_framework' ]
-
使用
# urls.py from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('books/', views.Books.as_view(), name='books'), path('books/<int:book_id>/', views.Books.as_view(), name='books'), ] # views.py from rest_framework.views import APIView from app01 import models import json class Books(APIView): @property def book_id_error(self): return [{'status': 404, 'msg': 'book_id不存在'}] @staticmethod def data_process(queryset_obj): re_list = [] for item in queryset_obj: re_dict = {} re_dict.update(item.__dict__) re_dict.pop('_state') re_list.append(re_dict) return re_list def get(self, request, book_id=None): if not book_id: book_queryset = models.Book.objects.all() else: book_queryset = models.Book.objects.filter(pk=book_id) re_list = self.data_process(book_queryset) if book_queryset else self.book_id_error return JsonResponse(re_list, safe=False)