day74作业

models.py

from django.db import models


# Create your models here.

class BaseModel(models.Model):
    is_delete = models.BooleanField(default=False)
    created_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        abstract = True


class Car(BaseModel):
    name = models.CharField(max_length=64, blank=True)
    img = models.ImageField(upload_to='img', default='img/default.jpg')
    price = models.DecimalField(max_digits=10, decimal_places=2)

    store = models.ForeignKey(to='CarStore', related_name='cars', on_delete=models.DO_NOTHING, db_constraint=False, null=True)
    sponsors = models.ManyToManyField(to='Sponsor', related_name='cars')

    def __str__(self):
        return self.name

    @property
    def icon(self):
        from django.conf import settings
        return "%s%s%s" % (settings.BASE_URL, settings.MEDIA_URL, self.img)

    @property
    def store_info(self):
        return {
            'name': self.store.name,
            'address': self.store.address
        }

    @property
    def sponsor_list(self):
        sponsor_tmp_list = []
        sponsors = self.sponsors.all()
        for sponsor in sponsors:
            sponsor_dic = {
                'name': sponsor.name
            }
            try:
                sponsor_dic['phone'] = sponsor.detail.phone
            except:
                sponsor_dic['phone'] = '无'

            sponsor_tmp_list.append(sponsor_dic)
        return sponsor_tmp_list


class CarStore(BaseModel):
    name = models.CharField(max_length=64)
    address = models.CharField(max_length=64)

    def __str__(self):
        return self.name


class Sponsor(BaseModel):
    name = models.CharField(max_length=64)

    def __str__(self):
        return self.name


class SponsorDetail(BaseModel):
    phone = models.CharField(max_length=64)
    detail = models.OneToOneField(to=Sponsor, related_name='detail', on_delete=models.CASCADE, db_constraint=False)

二次封装response.py

from rest_framework.response import Response


class APIResponse(Response):
    def __init__(self, status=0, msg='ok', results=None, http_status=None,
                 headers=None,
                 exception=False, content_type=None, **kwargs):
        data = {
            'status': status,
            'msg': msg
        }

        if results is not None:
            data['results'] = results

        data.update(**kwargs)

        super().__init__(data=data, status=http_status, headers=headers, exception=exception, content_type=content_type)

exception.py

from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response


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

    else:
        response.data = {'detail': detail}

    return response

serializer.py

from rest_framework import serializers
from . import models


class CarListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        return super().create(validated_data)

    def update(self, instance_list, validated_data_list):
        return [
            self.child.update(instance_list[index], attrs) for index, attrs in enumerate(validated_data_list)
        ]

class StoreListSerializer(serializers.ListSerializer):
    def create(self, validated_data):
        return super().create(validated_data)

    def update(self, instance_list, validated_data_list):
        return [
            self.child.update(instance_list[index],attrs) for index, attrs in enumerate(validated_data_list)
        ]


class CarModelSerializer(serializers.ModelSerializer):
    class Meta:
        list_serializer_class = CarListSerializer
        model = models.Car
        fields = ['name', 'price', 'icon', 'store_info', 'sponsor_list']
        extra_kwargs = {
            'store': {'write_only': True},
            'sponsors': {'write_only': True}
        }


class StoreModelSerializer(serializers.ModelSerializer):
    cars = CarModelSerializer(many=True)
    class Meta:
        list_serialize_class = StoreListSerializer
        model = models.CarStore
        fields = ['name', 'address', 'cars']
        extra_kwargs = {

        }

urls.py


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

    url(r'^stores/$', views.CarStoreAPIView.as_view()),
    url(r'^stores/(?P<pk>\d+)/$', views.CarStoreAPIView.as_view())

]

views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from . import models
from .response import APIResponse
from . import serializer


class CarAPIView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            car_obj = models.Car.objects.filter(is_delete=False, pk=pk).first()
            if not car_obj:
                return APIResponse(status=1, msg='pk error')
            car_ser = serializer.CarModelSerializer(car_obj)

        else:
            car_query = models.Car.objects.filter(is_delete=False).all()
            car_ser = serializer.CarModelSerializer(car_query, many=True)
        return APIResponse(results=car_ser.data)

    def post(self, request, *args, **kwargs):
        if isinstance(request.data, dict):
            many = False
        elif isinstance(request.data, list):
            many = True
        else:
            return Response(data={'detail': '数据有误'}, status=400)

        car_ser = serializer.CarModelSerializer(data=request.data, many=many)
        car_ser.is_valid(raise_exception=True)
        car_obj_or_list = car_ser.save()
        return APIResponse(results=serializer.CarModelSerializer(car_obj_or_list, many=many).data)

    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            pks = [pk]
        else:
            pks = request.data
        try:
            rows = models.Car.objects.filter(is_delete=False, pk__in=pks).update(is_delete=True)
        except:
            return APIResponse(status=1, msg='数据有误')
        if rows:
            return APIResponse(status=0, msg='删除成功')
        return APIResponse(status=1, msg='删除失败')

    def patch(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                car_instance = models.Car.objects.filter(is_delete=False, pk=pk).first()
            except:
                return Response(data={'detail': 'pk error'}, status=400)

            car_ser = serializer.CarModelSerializer(instance=car_instance, data=request.data, partial=True,
                                                    context={'request': request})
            car_ser.is_valid(raise_exception=True)
            car_obj = car_ser.save()
            return APIResponse(results=serializer.CarModelSerializer(car_obj).data)

        else:
            request_data = request.data
            try:
                pks = []
                for dic in request_data:
                    pk = dic.pop('pk')
                    pks.append(pk)

                car_query = models.Car.objects.filter(is_delete=False, pk__in=pks).all()
                if len(pks) != len(car_query):
                    raise Exception('pk对应的数据不存在')

            except Exception as e:
                return Response(data={'detail': '%s' % e}, status=400)

            car_ser = serializer.CarModelSerializer(instance=car_query, data=request_data, many=True, partial=True)
            car_ser.is_valid(raise_exception=True)
            car_list = car_ser.save()
            return APIResponse(results=serializer.CarModelSerializer(car_list, many=True).data)


class CarStoreAPIView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            store_obj = models.CarStore.objects.filter(is_delete=False, pk=pk).first()
            store_ser = serializer.StoreModelSerializer(store_obj)

        else:
            store_query = models.CarStore.objects.filter(is_delete=False).all()
            store_ser = serializer.StoreModelSerializer(store_query, many=True)
        return APIResponse(results=store_ser.data)


    def post(self, request, *args, **kwargs):
        if isinstance(request.data, dict):
            many = True
        elif isinstance(request.data, list):
            many = True
        else:
            return Response(data={'detail': '数据有误'}, status=400)

        store_ser = serializer.StoreModelSerializer(data=request.data, many=many)
        store_ser.is_valid(raise_exception=True)
        store_obj_or_list = store_ser.save()
        return APIResponse(results=serializer.StoreModelSerializer(store_obj_or_list, many=many).data)
posted @ 2019-12-30 11:58  SetCreed  阅读(65)  评论(0编辑  收藏