day 74 作业

day 74 作业

model


from django.db import models

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


class Car(BaseModel):
    name = models.CharField(max_length=64)
    price = models.DecimalField(max_digits=10,decimal_places=2)

    brands = models.ForeignKey(to='Brand',related_name='cars',db_constraint=False,on_delete=models.DO_NOTHING)
    sponsors = models.ManyToManyField(to='Sponsor',db_constraint=False,related_name='cars')

    @property
    def brands_info(self):
        return {
            'name':self.brands.name,
            'address':self.brands.address
        }

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

            sponsors_list_temp.append(sponsor_dict)
        return sponsors_list_temp


class Brand(BaseModel):
    name = models.CharField(max_length=255)
    address = models.CharField(max_length=255)


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


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

view

# Create your views here.
from .response import APIResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from . import models
from . import serializer


class CarsAPIView(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(1, 'error', http_status=400)
            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 APIResponse(1, '数据有误', http_status=400)
        car_ser = serializer.CarModelSerializer(data=request.data, many=many)
        car_ser.is_valid(raise_exception=True)
        car_obj = car_ser.save()
        return APIResponse(results=serializer.CarModelSerializer(car_obj, many=many).data)

    def patch(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            try:
                car_obj = models.Car.objects.get(is_delete=False,pk=pk)
            except:
                return APIResponse(1,'pk error',http_status=400)
            car_ser = serializer.CarModelSerializer(instance=car_obj,data=request.data,partial=True)
            car_ser.is_valid(raise_exception=True)
            car_obj = car_ser.save()
            return APIResponse(results=serializer.CarModelSerializer(car_obj).data)
        else:
            try:
                pks = []
                for dic in request.data:
                    pks.append(dic.pop('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({'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_obj = car_ser.save()
            return APIResponse(results=serializer.CarModelSerializer(car_obj,many=True).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(1,'数据有误')
        if rows:
            return APIResponse(msg='删除成功')
        return APIResponse(1,'删除失败')


ser

from rest_framework import serializers
from api import models

class CarListSerializer(serializers.ListSerializer):
    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','brands','sponsors','brands_info','sponsors_list']
        extra_kwargs = {
            'brands':{
                'write_only':True,
            },
            'sponsors':{
                'write_only': True
            }
        }

posted @ 2019-12-29 23:00  🍞面包🍞  阅读(97)  评论(0编辑  收藏  举报