项目模型类创建 | Django

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了项目模型类创建 | Django相关的知识,希望对你有一定的参考价值。

# 在线教育网站项目
# -----------------------------------------------------||基础设置
1.apps设置
    user 用户管理
    course 课程管理
    organization 机构和教室管理
    operation 用户操作管理
2.建立虚拟环境
    mkvirtualenv mxonlie --python=/usr/bin/python3 
    pip install django
3.建立项目
    MxOnline
4.安装mysql驱动
    sudo pip install pymysql
5.数据库配置
    DATABASES = {
        default: {
            ENGINE: django.db.backends.mysql,
            NAME: mxonline,
            USER: root,
            PASSWORD: mysql,
            HOST: localhost,
            POST: 3306,
        }
    }
6.数据库迁移
    makemigrations
    migrate
7.打开debug模式
    # 确认服务器运行成功
    
# -----------------------------------------------------|| users
1.创建应用
    startapp users
2.添加应用至settings.py
    users
3.设计表结构
    # django自带user表,auth_user中包含默认字段有:
    #     password,last_login,is_superuser,username,
    #     first_name,last_name,email,is_staff,is_active,deta_joined
    1.分析网站需要的user字段
        # 自定义user表
        # 继承django内置user表的类AbstractUser
        from django.contrib.auth.models import AbstractUser
        
        class UserProfile(AbstractUser):
            # 添加自己需要但是默认表中不具备的字段
            nick_name = models.CharField(max_lengh=50, verbose_name="")
            # 该字段可以不填,因为用户注册的时候不需要输入
            birth = models.DateField(verbose_name="生日", null=True, blank=True)
            # CharField字段一定要加上长度限制
            gender = models.CharField(
                    max_lengh=6,
                    choices=(
                    (male, ),
                    (female, )),
            )
            address = models.CharField(max_length=100, default="")
            mobile = models.CharField(max_lengh=11, null=True, blank=True)
            # 头像文件字段,当没有头像的时候需要一个默认的头像
            # ImageField字符需要安装pillow包
            image = models.ImageField(upload_to="image/%Y/%m", default="image/default.png", max_lengh=100)
            
            class Meta:
                verbose_name = "用户信息"
                verbose_name_plural = verbose_name
                
            def __str__(self):
                return self.username
                
    2.重载表结构需要添加设置
        AUTH_USER_MODEL = "users.UserProfile"  # app+模型类
    3.迁移
        # 先把原有的表统统删除
    4.注册登录需要用到一张邮箱验证码表,只与user表相关
        # 导入包分三个区域,1.python;2.django;3.自定义的包
        from datetime import datetime
        
        class EmailVerifyRecord(models.Model):
            code = models.CharField("验证码", max_length=20)
            email = models.EmailField("邮箱", max_lengh=50)
            # 发送类型:注册,找回密码等
            send_type = models.CharField(
                "发送类型",
                choices=(
                ("register", "注册"),
                ("forget", "忘记密码")
                )
            )
            send_time = models.DateTimeField("发送时间", default=datetime.now)
            # now不加‘()‘在实例化时生成,而不是model编译的时候
        
            class Meta:
                verbose_name = "邮箱验证码"
                verbose_name_plural = verbose_name
        
    5.首页轮播图,是一个独立的功能,可以放在user当中
        class Banner(models.Model):
            title = models.CharField("标题", max_lengh=100)
            # 因为image在数据库中保存的也是char格式,所以添加最大长度
            image = models.ImageField("轮播图", upload_to="banner/%Y/%m", max_lengh=100)
            url = models.URLField("访问地址", max_lengh=200)
            index = models.IntegerField("顺序", default=100)
            add_time = models.DateTimeField("添加时间", default=datetime.now)
            
            class Meta:
                verbose_name = "轮播图"
                verbose_name_plural = verbose_name
                
            def __str__(self):
                return self.title
        
4.循环引用,出错 -->> 分成设计
    courses,organization,users -->> operation
    # 将用户点赞评论等功能写到operation表中
    
# -----------------------------------------------------|| course
# 课程 -> 章节 -> 视频  一对多
# 课程 -> 资源下载  一对多
# 4张表
    class Course(models.Model):
        name = models.CharField("课程名", max_length=50)
        desc = models.CharField("课程描述", max_length=300)
        detail = models.TextField("课程详情")
        degree = models.CharField(
            "课程等级",
            choices=(
                ("cj", "初级"),
                ("zj", "中级"),
                ("gj", "高级")
            )
        )
        learn_time = models.IntegerField("学习时长", default=0)
        students = models.IntegerField("学习人数", default=0)
        fav_nums = models.IntegerField("收藏人数", default=0)
        image = models.ImageField("封面图", upload_to="courses/%Y/%m", max_length=100)
        click_nums = models.IntegerField("点击数", default=0)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "课程"
            verbose_name_plural = verbose_name

        def __str__(self):
            return self.name


    class Lesson(models.Model):
        course = models.ForeignKey(Course, verbose_name="课程")
        name = models.CharField("章节名", max_length=100)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "章节"
            verbose_name_plural = verbose_name

        def __str__(self):
            return self.name


    class Video(models.Model):
        lesson = models.ForeignKey(Lesson, verbose_name="章节")
        name = models.CharField("视频名称", max_length=100)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "视频"
            verbose_name_plural = verbose_name

        def __str__(self):
            return self.name


    class CourseResource(models.Model):
        course = models.ForeignKey(Course, "课程")
        name = models.CharField("资源名称", max_length=100)
        download = models.FileField("上传地址", upload_to="course/resource/%Y/%m", max_length=100)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "课程资源"
            verbose_name_plural = verbose_name

        def __str__(self):
            return self.name

# -----------------------------------------------------|| organization
    class CourseOrg(models.Model):
        """课程机构"""
        name = models.CharField("机构名称", max_length=50)
        desc = models.TextField("机构描述")
        click_nums = models.IntegerField("点击数", default=0)
        fav_nums = models.IntegerField("收藏数", default=0)
        image = models.ImageField("封面图", upload_to="org/%Y/%m")
        address = models.CharField("机构地址", max_lengh=150)
        city = models.ForeignKey(CityDict, verbose_name="所在城市", )
        add_time = models.DateTimeField(default=datetime.now)

        class Meta:
            verbose_name = "课程机构"
            verbose_name_plural = verbose_name

        def _str__(self):
            return self.name


    class CityDict(models.Model):
        name = models.CharField("城市", max_lengh=20)
        desc = models.CharField("描述", max_length=200)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "城市"
            verbose_name_plural = verbose_name

        def _str__(self):
            return self.name


    class Teacher(models.Model):
        org = models.ForeignKey(CourseOrg, verbose_name="所属机构")
        name = models.CharField("教室名", max_lengh=50)
        work_years = models.IntegerField("工作年限", default=0)
        work_company = models.CharField("就业公司", max_length=50)
        work_position = models.CharField("工作职位", max_length=50)
        points = models.CharField("教学特点", max_length=50)
        click_nums = models.IntegerField("点击数", default=0)
        fav_nums = models.IntegerField("收藏数", default=0)
        add_time = models.DateTimeField(default=datetime.now)

        class Meta:
            verbose_name = "教室"
            verbose_name_plural = verbose_name

        def _str__(self):
            return self.name
    

# -----------------------------------------------------|| operation
# UserAsk 用户咨询表 CourseComments 用户评论 UserFavorite 用户收藏
# UserMessage 用户消息 UserCourse 用户学习的课程
    class UserAsk(models.Model):
        name = models.CharField("姓名", max_length=20)
        mobile = models.CharField("手机", max_length=50)
        course_name = models.CharField("课程名", max_length=50)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "用户咨询"
            verbose_name_plural = verbose_name
            
        def __str__(self):
            return self.name

    
    from courses.models import Course
    from users.models import UserProfile
    
    class CourseComments(models.Model):
        "课程评论"
        # 肯定涉及到user用户,以及course课程
        user = models.ForeignKey(UserProfile, verbose_name="用户")
        course = models.ForeignKey(Course, verbose_name="课程")
        comments = models.CharField("评论", max_length=200)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "课程评论"
            verbose_name_plural = verbose_name
            
        def __str__(self):
            return self.name

    
    class UserFavorite(models.Model):
        user = models.ForeignKey(UserProfile, verbose_name="用户")
        # 在收藏表里存一个数字,获取指定表中id=fav_id的数据?
        fav_id = models.IntegerField("数据id", default=0)
        fav_type = models.IntegerField(
            "收藏类型",
            choices=(
                (1, "课程"),
                (2, "课程机构"),
                (3, "讲师")
            ),
            default=1
        )
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "课程收藏"
            verbose_name_plural = verbose_name
            
        def __str__(self):
            return self.name

    
    # 用户消息表
    class UserMessage(models.Model):
        user = models.IntegerField("接受用户", default=0)
        message = models.CharField("消息内容", max_length=500)
        # 消息是否已读
        has_read = models.BooleanField("是否已读", default=False)
        add_time = models.DateTimeField("添加时间", default=datetime.now)

        class Meta:
            verbose_name = "用户消息"
            verbose_name_plural = verbose_name
            
        def __str__(self):
            return self.name

    
    class UserCourse(models.Model):
        user = models.ForeignKey(UserProfile, verbose_name="用户")
        course = models.ForeignKey(Course, verbose_name="课程")
        add_time = models.DateTimeField("添加时间", default=datetime.now)
        
        class Meta:
            verbose_name = "用户课程"
            verbose_name_plural = verbose_name
            
        def __str__(self):
            return self.name
    # 外部导入的模块中类作为外键不要加""

 

以上是关于项目模型类创建 | Django的主要内容,如果未能解决你的问题,请参考以下文章

django数据库反向生成类

Django使用数据库表反向生成models类

Django框架02:模型与站点

美多商城项目 02用户注册

网站开发(周四):项目后台数据管理(实战)

开源web框架django知识总结