Exercise 03

operation

  • Django a new item, define a Car class, attributes have a name string, int select Properties Color (0: Silver, 1: Black, 2: Red, 3: gray), the full decimal precision. Price type, image type of image file, brand brand string type
  • Based ModelSerializer class, complete Car resources of a single check, group check, single by the interface sequence: Show car name, car color, car prices, car posters, car brand, de-serialization: You must provide a car name, car the price of the car brand (car matching the need for secondary confirmation re_brand), the default color for the silver car (can be provided), car posters need not be provided (blank by default)

# models文件中
from django.db import models

class Car(models.Model):
    """
    name字符串属性,
    color整型选择属性(0:银色,1:黑色,2:红色,3:灰色),
    price全精度小数类型,
    image图片文件类型,
    brand字符串类型
    """
    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.png')
    brand = models.CharField(max_length=64)

    @property
    def car_color(self):
        return self.get_color_display()

# 应用的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()),
]

    
    
# 自定义的序列化文件中
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
    
    
# views文件中

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()
        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
        })

Guess you like

Origin www.cnblogs.com/Mcoming/p/12103895.html
03
03