day 74作业

China☆狼群 提交于 2020-01-05 23:50:30

作业

'''
1、完成汽车系统表模型的建立(表关系自己设计)
    汽车表、汽车商家表、赞助商表、赞助商详情表

2、完成汽车系统的接口编写
    汽车表:八大接口(不需要写put方法)
    汽车商家表:八大接口(不需要写put方法)
表关系梳理:
    - 汽车厂商与汽车:一对多
    - 汽车与赞助商:多对多
    - 赞助商与赞助商详情:一对一
'''

模型类配置

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=255)
    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')

路由配置

项目主路由:

from django.conf.urls import url,include
from django.contrib import admin


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


api、urls.py:
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^v1/cars/$',views.CarsAPIView.as_view()),
    url(r'^v1/cars/(?P<pk>\d+)/$',views.CarsAPIView.as_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):
        '''
        单查接口测试:http://127.0.0.1:8000/api/v1/cars/1/
        群查接口测试:http://127.0.0.1:8000/api/v1/cars/
        '''
        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):
        '''
        单增接口测试:http://127.0.0.1:8000/api/v1/cars/
            - 携带数据包
                {
                    "name":"奔驰",
                    "price":"6666.66",
                    "brands":1,
                    "sponsors":[1,2]
                }

        群增接口测试:http://127.0.0.1:8000/api/v1/cars/
            - 携带数据包
                [
                    {
                        "name": "宝马",
                        "price": "8888.88",
                        "brands": 1,
                        "sponsors": [
                            1
                        ]
                    },
                    {
                        "name": "保时捷",
                        "price": "9999.99",
                        "brands": 2,
                        "sponsors": [
                            2
                        ]
                    }
                ]
        '''
        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):
        '''
        单改接口测试: http://127.0.0.1:8000/api/v1/cars/1/
            - 携带数据包参数
                {
                    "name":"奔驰1"
                },
        群改接口测试:
            - 携带数据包参数
                [{
                    "pk":1,
                    "name":"奔驰2"
                },
                {
                    "pk":2,
                    "name":"奔驰3"
                }]
        '''
        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):
        '''
        单删接口测试:http://127.0.0.1:8000/api/v1/cars/1/

        群接口测试:http://127.0.0.1:8000/api/v1/cars/
            携带数据包参数
                [2,3]
        '''
        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,'删除失败')

序列化类配置

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
            }
        }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!