Django模型类之models字段类型和参数以及元数据meta

models之字段类型和参数

示例:

# class Test(models.Model):  # courses_test
#     """测试学习用"""
#     # Auto = models.AutoField()  # 自增长字段
#     # BigAuto = models.BigAutoField()
#
#     # 二进制数据
#     Binary = models.BinaryField()
#
#     # 布尔型
#     Boolean = models.BooleanField()
#     NullBoolean = models.NullBooleanField()
#
#     # 整型
#     PositiveSmallInteger = models.PositiveSmallIntegerField(db_column="age")  # 5个字节
#     SmallInteger = models.SmallIntegerField(primary_key=False)  # 6个字节
#     PositiveInteger = models.PositiveIntegerField()  # 10个字节
#     Integer = models.IntegerField(verbose_name="11个字节大小")  # 11个字节
#     BigInteger = models.BigIntegerField(unique=True)  # 20个字节
#
#     # 字符串类型
#     Char = models.CharField(max_length=100, null=True, blank=True, db_index=True)  # varchar
#     Text = models.TextField(help_text="这个是longtext")  # longtext
#
#     # 时间日期类型
#     Date = models.DateField(unique_for_date=True, auto_now=True)  #自动填入最新时间
#     DateTime = models.DateTimeField(editable=False, unique_for_month=True, auto_now_add=True)
#     Duration = models.DurationField()  # int, Python timedelta实现
#
#     # 浮点型
#     Float = models.FloatField()
#     Decimal = models.DecimalField(max_digits=4, decimal_places=2)  # 11.22, 16.34
#
#     # 其它字段
#     Email = models.EmailField()  # 邮箱
#     Image = models.ImageField()
#     File = models.FileField()
#     FilePath = models.FilePathField()
#     URL = models.URLField()
#     UUID = models.UUIDField()
#     GenericIPAddress = models.GenericIPAddressField()
#
#
# class A(models.Model):
#     onetoone = models.OneToOneField(Test, related_name="one")
#
#
# on_delete 六种模式
# class B(models.Model):
#     foreign = models.ForeignKey(A, on_delete=models.CASCADE)  # 删除级联
#     # foreign = models.ForeignKey(A, on_delete=models.PROTECT)
#     # foreign = models.ForeignKey(A, on_delete=models.SET_NULL, null=True, blank=True)  # 删除置空
#     # foreign = models.ForeignKey(A, on_delete=models.SET_DEFAULT, default=0)
#     # foreign = models.ForeignKey(A, on_delete=models.DO_NOTHING)
#     # foreign = models.ForeignKey(A, on_delete=models.SET)
#
#
# class C(models.Model):
#     manytomany = models.ManyToManyField(B)


# 1.所有字段都有的参数
# 2.个别字段才有的参数
# 3.关系型字段的参数

"""
on_delete 当一个被外键关联的对象被删除时,Django将模仿on_delete参数定义的SQL约束执行相应操作
    如下6种操作
    CASCADE:模拟SQL语言中的ON DELETE CASCADE约束,将定义有外键的模型对象同时删除!(该操作为当前Django版本的默认操作!)
    PROTECT:阻止上面的删除操作,但是弹出ProtectedError异常
    SET_NULL:将外键字段设为null,只有当字段设置了null=True时,方可使用该值。
    SET_DEFAULT:将外键字段设为默认值。只有当字段设置了default参数时,方可使用。
    DO_NOTHING:什么也不做。
    SET():设置为一个传递给SET()的值或者一个回调函数的返回值。注意大小写。
"""
View Code

 

实际创建表单示例:

from django.db import models

# Create your models here.

class AddressInfo(models.Model):  # coures_addressinfo
    """省市县地址信息"""
    address = models.CharField(max_length=200, null=True, blank=True, verbose_name="地址")
    pid = models.ForeignKey('self', null=True, blank=True, verbose_name="自关联",on_delete=models.SET_NULL)
    # pid = models.ForeignKey('AddressInfo', null=True, blank=True, verbose_name="自关联")
    note = models.CharField(max_length=200, null=True, blank=True, verbose_name="说明")

    def __str__(self):  # __unicode__(self)
        return self.address

    class Meta:
        # 定义元数据
        db_table = 'address'
        # ordering = ['pid']  # 指定按照什么字段排序
        verbose_name = '省市县地址信息'
        verbose_name_plural = verbose_name
        # abstract = True
        # permissions = (('定义好的权限', '权限说明'),)
        # managed = False
        unique_together = ('address', 'note')  # ((),())
        # app_label = 'courses'
        # db_tablespace  # 定义数据库表空间的名字


class Teacher(models.Model):
    """讲师信息表"""
    nickname = models.CharField(max_length=30, primary_key=True, db_index=True, verbose_name="昵称")
    introduction = models.TextField(default="这位同学很懒,木有签名的说~", verbose_name="简介")
    fans = models.PositiveIntegerField(default="0", verbose_name="粉丝数")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "讲师信息表"
        verbose_name_plural = verbose_name

    def __str__(self):  # Python2:__unicode__
        return self.nickname


class Course(models.Model):
    """课程信息表"""
    title = models.CharField(max_length=100, primary_key=True, db_index=True, verbose_name="课程名")
    teacher = models.ForeignKey(Teacher, null=True, blank=True, on_delete=models.CASCADE,
                                verbose_name="课程讲师")  # 删除级联
    type = models.CharField(choices=((1, "实战课"), (2, "免费课"), (0, "其它")), max_length=12,
                            default=0, verbose_name="课程类型")
    price = models.PositiveSmallIntegerField(verbose_name="价格")
    volume = models.BigIntegerField(verbose_name="销量")
    online = models.DateField(verbose_name="上线时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "课程信息表"
        get_latest_by = "created_at"
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.get_type_display()}-{self.title}"  # 示例:实战课-Django零基础入门到实战
        # return "{}-{}".format(self.get_type_display(), self.title)  # 示例:实战课-Django零基础入门到实战


class Student(models.Model):
    """学生信息表"""
    nickname = models.CharField(max_length=30, primary_key=True, db_index=True, verbose_name="昵称")
    course = models.ManyToManyField(Course, verbose_name="课程")
    age = models.PositiveSmallIntegerField(verbose_name="年龄")
    gender = models.CharField(choices=((1, ""), (2, ""), (0, "保密")), max_length=1,
                              default=0, verbose_name="性别")
    study_time = models.PositiveIntegerField(default="0", verbose_name="学习时长(h)")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "学生信息表"
        ordering = ['age']
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.nickname


class TeacherAssistant(models.Model):
    """助教信息表"""
    nickname = models.CharField(max_length=30, primary_key=True, db_index=True, verbose_name="昵称")
    teacher = models.OneToOneField(Teacher, null=True, blank=True, on_delete=models.SET_NULL,
                                   verbose_name="讲师")  # 删除置空
    hobby = models.CharField(max_length=100, null=True, blank=True, verbose_name="爱好")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "助教信息表"
        db_table = "courses_assistant"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.nickname
View Code

 

简单查询语句等

 # # 1.查询、检索、过滤
        # teachers = Teacher.objects.all()
        # print(teachers)
        # teacher2 = Teacher.objects.get(nickname='Jack')  # get()只能返回一条结果,多条则会报错
        # print(teacher2, type(teacher2))
        # teacher3 = Teacher.objects.filter(fans__gte=500)  # QuerySet, 可以是多条结果
        # for t in teacher3:
        #     print(f"讲师姓名{t.nickname}--粉丝数{t.fans}")
        # # 2.字段数据匹配,大小写敏感
        # teacher4 = Teacher.objects.filter(fans__in=[666, 1231])
        # print(teacher4)
        # teacher5 = Teacher.objects.filter(nickname__icontains='A')
        # print(teacher5)
        # # 3.结果切片、排序、链式查询
        # print(Teacher.objects.all()[:1])
        # teacher6 = Teacher.objects.all().order_by('-fans')
        # for t in teacher6:
        #     print(t.fans)
        # print(Teacher.objects.filter(fans__gte=500).order_by('nickname'))
        # # 4.查看执行的原生SQL
        # print(str(Teacher.objects.filter(fans__gte=500).order_by('nickname').query))
        # """SELECT `courses_teacher`.`nickname`, `courses_teacher`.`introduction`, `courses_teacher`.`fans`,
        # `courses_teacher`.`created_at`, `courses_teacher`.`updated_at` FROM `courses_teacher`
        # WHERE `courses_teacher`.`fans` >= 500 ORDER BY `courses_teacher`.`nickname` ASC
        # """
        """返回新QuerySet API"""
        # 1.all(), filter(), order_by(), exclude(), reverse(), distinct()
        # s1 = Student.objects.all().exclude(nickname='A同学')
        # for s in s1:
        #     print(s.nickname, s.age)
        # s2 = Student.objects.all().exclude(nickname='A同学').reverse()
        # for s in s2:
        #     print(s.nickname, s.age)

        # 2.extra(), defer(), only() 实现字段别名,排除一些字段,选择一些字段
        # s3 = Student.objects.all().extra(select={"name": "nickname"})
        # for s in s3:
        #     print(s.name)
        # print(str(Student.objects.all().only('nickname', 'age').query))

        # 3.values(), values_list() 获取字典或元组形式的QuerySet
        # print(TeacherAssistant.objects.values('nickname', 'hobby'))
        # print(TeacherAssistant.objects.values_list('nickname', 'hobby'))
        # print(TeacherAssistant.objects.values_list('nickname', flat=True))

        # 4.dates(), datetimes()  根据时间日期获取查询集
        # print(Course.objects.dates('created_at', 'year', order='DESC'))
        # print(Course.objects.datetimes('created_at', 'year', order='DESC'))

        # 5.union(), intersection(), difference() 并集、交集、差集
        # p_240 = Course.objects.filter(price__gte=240)
        # p_260 = Course.objects.filter(price__lte=260)
        # print(p_240.union(p_260))
        # print(p_240.intersection(p_260))
        # print(p_240.difference(p_260))

        # 6.select_related() 一对一、多对一查询优化, prefetch_related() 一对多、多对多查询优化;反向查询
        # courses = Course.objects.all().select_related('teacher')
        # for c in courses:
        #     print(f"{c.title}--{c.teacher.nickname}--{c.teacher.fans}")

        # students = Student.objects.filter(age__lt=30).prefetch_related('course')
        # for s in students:
        #     print(s.course.all())
        # print(Teacher.objects.get(nickname="Jack").course_set.all())

        # 7.annotate() 使用聚合计数、求和、平均数 raw() 执行原生的SQL
        # print(Course.objects.values('teacher').annotate(vol=Sum('volume')))
        # print(Course.objects.values('teacher').annotate(pri=Avg('price')))

        # """不返回Query API"""
        # # 1.获取对象 get(), get_or_create(), first(), last(), latest(), earliest(), in_bulk()
        # print(Course.objects.first())
        # print(Course.objects.last())
        # print(Course.objects.earliest())
        # print(Course.objects.latest())
        # print(Course.objects.in_bulk(['Python系列教程4', 'Golang系列教程1']))
        #
        # # 2.创建对象 create(), bulk_create(), update_or_create() 创建,批量创建,创建或更新
        #
        # # 3.更新对象 update(), update_or_create() 更新,更新或创建
        # Course.objects.filter(title='Java系列教程2').update(price=300)
        #
        # # 4.删除对象 delete() 使用filter过滤
        # Course.objects.filter(title='test').delete()
        #
        # # 5.其它操作 exists(), count(), aggregate() 判断是否存在,统计个数,聚合
        # print(Course.objects.filter(title='test').exists())
        # print(Course.objects.filter(title='Java系列教程2').exists())
        # print(Course.objects.count())
        # print(Course.objects.aggregate(Max('price'), Min('price'), Avg('price'), Sum('volume')))
        # courses = Course.objects.values('teacher').annotate(t=GroupConcat('title', distinct=True,
        #                                                                   ordering='title ASC',
        #                                                                   separator='-'))
        # for c in courses:
        #     print(c)

        # Course.objects.update(price=F('price') - 11)
        # print(Course.objects.filter(volume__lte=F('price') * 10))
        #
        # print(Course.objects.filter(Q(title__icontains='java') & Q(volume__gte=5000)))
        #
        # print(Course.objects.filter(Q(title__icontains='golang') | Q(volume__lte=1000)))
View Code

 

posted @ 2019-03-10 17:16  Mixtea  阅读(542)  评论(0编辑  收藏  举报