同一个视图相应不同的方法
from django.db import models # Create your models here. class Book(models.Model): nid=models.AutoField(primary_key=True) name=models.CharField(max_length=32) price=models.DecimalField(max_digits=5,decimal_places=2) def __str__(self): return self.name
#!/usr/bin/env python # -*- coding: utf-8 -*- from rest_framework import serializers from app01 import models class BookSerializer(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__'
from django.shortcuts import render # Create your views here. from app01 import models, mySer from rest_framework.viewsets import ViewSetMixin from rest_framework.views import APIView from rest_framework.response import Response class Book(ViewSetMixin, APIView): def get_all(self, request): response = {'status': 100, 'msg': '查询成功'} book_list = models.Book.objects.all() ser = mySer.BookSerializer(instance=book_list, many=True) response['data'] = ser.data return Response(response) def get_one(self, request, pk): response = {'status': 100, 'msg': '查询成功'} book_list = models.Book.objects.all().filter(pk=pk).first() if book_list: ser = mySer.BookSerializer(instance=book_list, many=False) response['data'] = ser.data else: response['status'] = 101 response['msg'] = '查询失败' return Response(response)
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^books/$',views.Book.as_view({'get':'get_all'}) ), url(r'^books/(?P<pk>d+)',views.Book.as_view({'get':'get_one'}) ), ]
在视图函数中,如果将
return Response (response) 转化为Json格式字符串,如下
return JsonResponse(response,safe=False)
自动生成路由视图验证
from django.db import models # Create your models here. class Book(models.Model): nid=models.AutoField(primary_key=True) name=models.CharField(max_length=32) price=models.DecimalField(max_digits=5,decimal_places=2) def __str__(self): return self.name
from django.conf.urls import url,include # include用作路由分发 from django.contrib import admin from app01 import views from rest_framework import routers # 实例化产生一个对象 router=routers.DefaultRouter() # 传两个参数 router.register('books',views.Book) urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^books/$',views.Book.as_view({'get':'get_all'}) ), # url(r'^books/(?P<pk>d+)',views.Book.as_view({'get':'get_one'}) ), url(r'',include(router.urls)) ]
from app01 import models, mySer from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet # 自动生成路由 class Book(ModelViewSet, APIView): queryset = models.Book.objects.all() serializer_class = mySer.BookSerializer
手写配置文件
有两套配置文件,默认配置,用户的配置
如果某个字段,用户配置了,就用用户的,如果没配置,就用默认的