models
from django.db import models class Car(models.Model): COLOR_CHOICES = [ (0, '银色'), (1, '黑色'), (2, '红色'), (3, '灰色') ] name = models.CharField(max_length=64) color = models.IntegerField(choices=COLOR_CHOICES,default=0) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='img', default='img/default.jpg') brand = models.CharField(max_length=64) @property def car_color(self): return self.get_color_display()
exception
from rest_framework.views import exception_handler as drf_exception_handler from rest_framework.response import Response from rest_framework import status def exception_handler(exc, context): response = drf_exception_handler(exc, context) detail = '%s - %s - %s' % (context.get('view'), context.get('request').method, exc) if not response: # 服务端错误 response = Response({'detail': detail}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: response.data = {'detail': detail} # 核心:要将response.data.get('detail')信息记录到日志文件 # logger.waring(response.data.get('detail')) import sys sys.stderr.write('异常:%s\n' % response.data.get('detail')) return response
serializer
from rest_framework import serializers from . import models class CarModelSerializer(serializers.ModelSerializer): re_brand = serializers.CharField(write_only=True) class Meta: model = models.Car fields = ['name', 'price','color','car_color', 'image', 'brand', 're_brand'] extra_kwargs = { 'image':{ 'read_only':True }, 'color':{ 'write_only':True } } def validate(self, attrs): brand = attrs.get('brand') re_brand = attrs.pop('re_brand') if brand != re_brand: raise serializers.ValidationError({'re_brand':'品牌不一致'}) return attrs
urls
from django.conf.urls import url from . import views urlpatterns = [ url(r'^cars/$',views.CarAPIView.as_view()), url(r'^cars/(?P<pk>\d+)/$',views.CarAPIView.as_view()), ]
views
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from. import models, serializers class CarAPIView(APIView): def get(self, request, *args, **kwargs): pk = kwargs.get('pk') if pk: car_obj = models.Car.objects.filter(pk=pk).first() # 如果查询对象不存在,直接返回错误信息 if not car_obj: return Response({ 'status':1, 'msg':'pk error' },status=400) car_ser = serializers.CarModelSerializer(car_obj) return Response({ 'status':0, 'msg':'ok', 'results':car_ser.data }) car_query = models.Car.objects.all() print(car_query) car_ser = serializers.CarModelSerializer(car_query,many=True) return Response({ 'status':0, 'msg':'ok', 'results':car_ser.data }) def post(self, request, *args, **kwargs): # 子序列化 car_ser = serializers.CarModelSerializer(data=request.data) car_ser.is_valid(raise_exception=True) car_obj= car_ser.save() return Response({ 'status':0, 'msg':'ok', 'results':serializers.CarModelSerializer(car_obj).data })
来源:https://www.cnblogs.com/shenblog/p/12103846.html