• 视图家族练习


    视图家族练习

    作业:

    1、整理今天所学知识点
    
    2、查看并研究ListAPIView工具视图类,继承该类完成汽车资源的群查接口,汽车资源需要有image资源,查看接口image资源的值
    
    
    3、研究GenericViewSet工具集,继承该类完成汽车资源的单查,群查,单增,单改,单删接口
    
    
    1、搭建Vue前台,集合序列化和视图家族,完成前后台分离的图书管理系统,前台页面可以用element-ui搭建,也可以采用bootstrap+jquery搭建
    

    modles.py

    from django.db import models
    
    class BaseModel(models.Model):
        is_delete = models.BooleanField(default=False)
        createdTime  = 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)
        brand = models.ForeignKey(to='Brand', db_constraint=False, null=True, on_delete=models.SET_NULL,
                                  related_name='cars')
        sponsors = models.ManyToManyField(to='Sponsor', db_constraint=False, related_name='cars')
        image = models.ImageField(upload_to= 'img',default='img/default.png')
    
        @property
        def img(self):
            from django.conf import settings
            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_temp = []
            for sponsor in self.sponsors.all():
                sponsor_dic = {
                    'name': sponsor.name
                }
                try:
                    sponsor_dic['phone'] = sponsor.detail.phone
                except:
                    sponsor_dic['phone'] = '未知'
                sponsor_list_temp.append(sponsor_dic)
            return sponsor_list_temp
    
        class Meta:
            verbose_name_plural = '汽车'
    
        def __str__(self):
            return self.name
    
    
    class Brand(BaseModel):
        name = models.CharField(max_length=64)
    
        class Meta:
            verbose_name_plural = '品牌'
    
        def __str__(self):
            return self.name
    
    
    class Sponsor(BaseModel):
        name = models.CharField(max_length=64)
    
        @property
        def phone(self):
            try:
                return self.detail.phone
            except:
                return "无"
    
        class Meta:
            verbose_name_plural = '赞助商'
    
        def __str__(self):
            return self.name
    
    
    class SponsorDetail(BaseModel):
        phone = models.CharField(max_length=11)
        sponsor = models.OneToOneField(to=Sponsor, db_constraint=False, on_delete=models.CASCADE, related_name='detail')
    
        class Meta:
            verbose_name_plural = '赞助商详情'
    
        def __str__(self):
            try:  # 连表可能会出现问题,所以要异常处理
                return self.sponsor.name + '的详情'
            except:
                return super().__str__()
    

    serializer.py

    
    from . import models
    from rest_framework import serializers
    
    class CarModelSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = models.Car
            fields = ('name', 'price', 'brand_name', 'sponsor_list', 'brand', 'sponsors','image')
    
            extra_kwargs = {
                'brand': {
                    'required': True,
                    'write_only': True
                },
                'sponsors': {
                    'required': True,
                    'write_only': True
                },
                'image': {
                    'read_only': True,
                    'required': True,
                },
            }
    
    

    urls.py:

    from django.conf.urls import url,include
    from django.contrib import admin
    from django.views.static import serve
    from .settings import MEDIA_ROOT
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^app01/', include('app01.urls')),
        url(r'^media/(?P<path>.*)', serve, {'document_root': MEDIA_ROOT}),
    
    ]
    
    
    from . import views
    from django.conf.urls import url
    
    
    urlpatterns = [
        url(r'^v1/cars/$', views.CarAPIView.as_view()),
        url(r'^v1/cars/(?P<pk>d+)/$', views.CarAPIView.as_view()),
    
    
        url(r'^cars/$', views.CarGenericViewSet.as_view({
            'get': 'list',
            'post': 'create',
        })),
        url(r'^cars/(?P<pk>d+)/$', views.CarGenericViewSet.as_view({
            'get': 'retrieve',
            'put': 'update',
            'patch': 'partial_update',
            'delete': 'destroy',
        })),
    
    ]
    

    views.py

    from django.shortcuts import render
    from rest_framework.response import Response
    from .response import APIResponse
    from rest_framework.views import APIView
    from . import models,serializer
    
    from rest_framework.mixins import ListModelMixin
    from rest_framework.generics import GenericAPIView
    
    class CarAPIView(GenericAPIView,ListModelMixin):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializer.CarModelSerializer
        lookup_field = 'pk'
    
        def get(self,request, *args,**kwargs):
            response = self.list(request, *args, **kwargs)
            return APIResponse(results=response.data)
    
    
    
    from rest_framework import mixins
    from rest_framework.viewsets import GenericViewSet
    class CarGenericViewSet(GenericViewSet,mixins.RetrieveModelMixin, mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializer.CarModelSerializer
    
        def retrieve(self,request, *args, **kwargs):
            response = self.retrieve(request, *args, **kwargs)
            return APIResponse(results=response.data)
    
        def post(self, request, *args, **kwargs):
            response = self.create(request, *args, **kwargs)
            return APIResponse(results=response.data)
    
        def update(self,request, *args, **kwargs):
            response = self.update(request, *args, **kwargs)
            return APIResponse(results=response.data)
    
        def list(self,request, *args, **kwargs):
            response = self.list(request, *args, **kwargs)
            return APIResponse(results=response.data)
    
        def partial_update(self,request, *args, **kwargs):
            response = self.partial_update(request, *args, **kwargs)
            return APIResponse(results=response.data)
    
        def destroy(self,request, *args, **kwargs):
            car_obj = self.get_object()
            car_obj.is_delete = True
            car_obj.save()
            return APIResponse(msg='删除成功')
    
    
  • 相关阅读:
    ctags cscope
    u-boot initf_bootstage函数分析
    u-boot log_init函数分析
    u-boot v2018.01 启动流程分析
    DECLARE_GLOBAL_DATA_PTR
    CaptchaCodeManager
    UserTokenManager JwtHelper
    AdminSwagger2Configuration
    logService
    AdminWebSessionManager AdminAuthorizingRealm ShiroConfig ShiroExceptionHandler
  • 原文地址:https://www.cnblogs.com/shaozheng/p/12126460.html
Copyright © 2020-2023  润新知