day75作业

# settings.py配置
TATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'api.exception.exception_handler'
}

BASE_URL = 'http://127.0.0.1:8000'
# 主路由
from django.conf.urls import url, include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include('api.urls')),

    url(r'^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_URL})
]

# 分路由
from django.conf.urls import url, include
from . import views

from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('v8/cars', views.CarModelViewSet, basename='car')

urlpatterns = [
    url(r'', include(router.urls))
]
# models模型
from django.db import models
from django.conf import settings

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)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    img = models.ImageField(upload_to='img', default='img/default.jpg')

    brand = models.ForeignKey(to='Brand', on_delete=models.SET_NULL, null=True, db_constraint=False,
                              related_name='cars')
    sponsors = models.ManyToManyField(to='Sponsor', db_constraint=False, related_name='cars')

    def __str__(self):
        return self.name

    @property
    def icon(self):
        return '%s%s%s' % (settings.BASE_URL, settings.MEDIA_URL, self.img)

    @property
    def brand_name(self):
        return self.brand.name

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

        return sponsor_list_tmp


class Brand(models.Model):
    name = models.CharField(max_length=64)

    def __str__(self):
        return self.name


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

    def __str__(self):
        return self.name


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

    def __str__(self):
        try:  # 连表可能会出现问题,所以要异常处理
            return self.sponsor.name + '的详情'
        except:
            return super().__str__()

# 序列化类
from rest_framework import serializers
from . import models


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

# 视图类

class CarModelViewSet(ModelViewSet):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializer.CarModelSerializer

    # 群整体改,群局部改,全删三个接口可以独立成三个方法
    def many_update(self, request, *args, **kwargs):
        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({'detail': '%s' % e}, status=400)
        car_ser = serializer.CarModelSerializer(instance=car_query, data=request_data, many=True)
        car_ser.is_valid(raise_exception=True)
        car_list = car_ser.save()
        return APIResponse(results=serializer.CarModelSerializer(instance=car_list, many=True).data)

    def many_partial_update(self, request, *args, **kwargs):
        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({'detail': '%s' % e}, status=400)
        car_ser = serializer.CarModelSerializer(instance=car_query, data=request_data, partial=True, many=True)
        car_ser.is_valid(raise_exception=True)
        car_list = car_ser.save()
        return APIResponse(results=serializer.CarModelSerializer(instance=car_list, many=True).data)

    def many_destroy(self, request, *args, **kwargs):
        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(0, '删除成功')
        return APIResponse(1, '删除失败')

    # 群增与单增必须公用一个接口,都要走create方法 - 重写create方法,用逻辑进行拆分
    def create(self, request, *args, **kwargs):
        if isinstance(request.data, list):
            car_ser = serializer.CarModelSerializer(data=request.data, many=True)
            car_ser.is_valid(raise_exception=True)
            car_obj = car_ser.save()
            return APIResponse(results=serializer.CarModelSerializer(car_obj, many=True).data)

        return super().create(request, *args, **kwargs)

    # destroy方法是完成is_delete字段值修改 - 重写destroy方法,自定义实现体
    def destroy(self, request, *args, **kwargs):
        car_obj = self.get_object()
        car_obj.is_delete = True
        car_obj.save()
        return APIResponse(msg='删除成功')

    # 让群查有状态码和状态信息 - 重写list方法
    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        return APIResponse(results=response.data)

    # 重写retrieve方法
    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        return APIResponse(results=response.data)
posted @ 2019-12-30 22:54  SetCreed  阅读(160)  评论(0编辑  收藏  举报