• 一个简易的drf的项目例子


                  luffy_city

    1.项目介绍

    今日内容:(路飞项目)
    
    1 contentType组件:
        路飞学成项目,有课程,学位课(不同的课程字段不一样),价格策略
    
        问题,1 如何设计表结构,来表示这种规则
                2 为专题课,添加三个价格策略
                  3 查询所有价格策略,并且显示对应的课程名称
                  4 通过课程id,获取课程信息和价格策略
            
        
    2 创建vue项目(目录结构介绍)
        1 node.js 安装
        2 vue脚手架:npm install -g @vue/cli
        3 vue create 项目名字
        4 用pycharm开发vue的项目
        5 项目目录结构:
            -node_modules  项目依赖
            -public      单页面开发(index是主页)
            -src   ---开发项目就跟它打交道
                -assets 放静态文件
                -components 放组件的
                -views     放的也是组件,但是他是页面组件
                -App.vue   主页面
                -main.js    项目主js(所有的配置,需要在里面写),入口
                -router.js  路由配置相关
                -store.js  vuex组件相关的,状态管理器
                -package.json  项目所有的依赖
        6 一个组件中,都会有三部分:
            -template   模板
            -script    写js代码
            -style     写样式
        7 element-ui
            -npm install element-ui
            -     
        
    3 vue跟django数据通信(axios)
    
        -npm install axios
    
    4 vue操作cookie并保存
        npm install vue-cookies
    
    5 登陆接口
    
    6 课程列表
        -vue路由携带参数跳转
        前面加一个冒号:后面传一个字典,指定name:路由的名字,params:是携带的参数
        
        <router-link :to="{name:'coursedetail',params:{'id':course.id}}">
            {{course.name}}
        </router-link>
        
    
    7 课程详情页面

    2.重点

     1、models.
    
      2、APIView
    
      3、ViewSetMixin
    
      4、serializers
    
      5、response
    
      6、utils ------response

    2、models

    from django.db import models
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.contenttypes.fields import GenericForeignKey,GenericRelation
    # Create your models here.
    
    class User(models.Model):
        name = models.CharField(max_length=32)
        pwd = models.CharField(max_length=32)
        type = models.ImageField(choices=((1,"common"),(2,"VIP"),(3,"SVIP")),default=1)
        bely = models.IntegerField()
        def __str__(self):
            return self.name
    
    class UserToken(models.Model):
        user = models.OneToOneField("User",on_delete=models.CASCADE)
        token = models.CharField(max_length=128)
    
    #专题课
    class Course(models.Model):
        '''
        专题课程
        唯一性约束,名字不能重复
        '''
        name = models.CharField(max_length=128,unique=True)
        course_img = models.CharField(max_length=255,verbose_name="课程图片")
        brief = models.CharField(max_length=128,verbose_name="课程概述")
        level_choices = ((0,"初级"),(1,"中级"),(2,"高级"))
        level = models.SmallIntegerField(choices=level_choices,default=1)
        pub_date = models.DateField(verbose_name="发布日期",blank=True,null=True)
        period = models.PositiveIntegerField(verbose_name="建议学习周期(days)",default=7)
        order = models.IntegerField("课程顺序",help_text="从上一个课程数字往后排")
        status_choices = ((0,"上线"),(1,"下线"),(2,"预上线"))
        status = models.SmallIntegerField(choices=status_choices,default=0)
        price_policy = GenericRelation("PricePolicy")
    
        def __str__(self):
            return self.name
    
        class Meta:
            verbose_name_plural = "专题课--"
    
    class CourseDetail(models.Model):
        course = models.OneToOneField("Course",on_delete=models.CASCADE)
        hours = models.IntegerField('课时')
        course_slogan = models.CharField(max_length=128,blank=True,null=True)
        recommend_courses = models.ManyToManyField("Course",related_name="recommend_by",blank=True)
        teachers = models.ManyToManyField("Teacher",verbose_name="课程讲师")
    
        def __str__(self):
            return self.course
    
        class Meta:
            verbose_name_plural = "课程详细"
    
    class PricePolicy(models.Model):
        '''
        价格与有课程小气表
        '''
        content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
        object_id = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type','object_id')
        valid_period_choices = ((1,"1 day"),(3,"3 天"),(7,"7天"))
        valid_period = models.SmallIntegerField(choices=valid_period_choices)
        price = models.FloatField()
    
        class Meta:
            unique_together = ("content_type","object_id","valid_period")
            verbose_name_plural = "价格策略"
    
        def __str__(self):
            return "%s(%s)%s"%(self.content_type,self.get_valid_period_display(),self.price)
    
    class Teacher(models.Model):
        name = models.CharField(max_length=32)
        image = models.CharField(max_length=128)
        brief = models.TextField(max_length=128)
    
        def __str__(self):
            return self.name
    
        class Meta:
            verbose_name_plural = "讲师"

    admin.py

    from django.contrib import admin
    
    # Register your models here.
    from app01 import models
    
    admin.site.register(models.Course)
    admin.site.register(models.CourseDetail)
    admin.site.register(models.PricePolicy)
    admin.site.register(models.Teacher)
    admin.site.register(models.User)
    admin.site.register(models.UserToken)

    urls.py

    from django.contrib import admin
    from django.urls import path
    from app01.views import courseview
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('course/', courseview.Course.as_view({'get':'get_all','post':'add_course'})),
        path('course/(?P<id>d+)', courseview.Course.as_view({'get':'get_one','delete':'deletecourse'})),
    ]

    views文件夹下的courseview.py

    from app01 import models
    from rest_framework.views import APIView
    from rest_framework.viewsets import ViewSetMixin
    from app01.Myser import CourseSer
    from rest_framework.response import Response
    from app01.utils import MyResponse
    
    class Course(ViewSetMixin,APIView):
    
        def get_all(self,request,*args,**kwargs):
            response = MyResponse()
            course_list = models.Course.objects.all()
            courseSer = CourseSer(instance=course_list,many=True)
            response.msg = "查询成功"
            response.data = courseSer.data
            return Response(response.get_dic)
    
        def get_one(self,request,*args,**kwargs):
            pass
        def add_course(self,request,*args,**kwargs):
            pass
        def deletecourse(self,request,*args,**kwargs):
            pass

    Myser.py

    from rest_framework import serializers
    from app01 import models
    
    class CourseSer(serializers.ModelSerializer):
        class Meta:
            model = models.Course
            fields  = '__all__'

    utils.py  作为工具

    class MyResponse():
        def __init__(self):
            self.status = 100
            self.msg = None
    
        @property
        def get_dic(self):
            return self.__dict__
  • 相关阅读:
    CentOS Python 安装MySQL-python
    Ubuntu64位安装Adobe Reader 9.5.5
    Codeforces Round #316 (Div. 2) (ABC题)
    cocos2dx 3.2+ 项目创建与问题总汇
    Mongodb的索引
    uva 12083 Guardian of Decency (二分图匹配)
    Linux查看内存使用量和交换区使用量
    053第423题
    [Python]xlrd 读取excel 日期类型2种方式
    求解组合问题的一个迭代算法
  • 原文地址:https://www.cnblogs.com/di2wu/p/10164665.html
Copyright © 2020-2023  润新知