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()的值或者一个回调函数的返回值。注意大小写。
"""

实际创建表单示例:

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="", 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="", 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

简单查询语句等

 # # 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)))

Django模型类之models字段类型和参数以及元数据meta的更多相关文章

  1. django 模型类的常见字段约束,以及filter 过滤和查询

    null 不设置时默认设置为False.设置为True时,数据库表字段中将存入NULL的记录. null和blank组合使用,null=True,blank=True,表示该字段可以为空 blank ...

  2. Django ORM中常用的字段类型以及参数配置

    一.数值型 AutoField对应int(11).自增主键,Django Model默认提供,可以被重写. BooleanField对应tinyint(1).布尔类型字段,一般用于记录状态标记. De ...

  3. Django(十)模型:django模型类对数据库的:增/删/改/查、自关联、管理器、元选项(指定表名)

    一.插入.更新和删除 调用一个模型类对象的save方法的时候就可以实现对模型类对应数据表的插入和更新. 调用一个模型类对象的delete方法的时候就可以实现对模型类对应数据表数据的删除. 二.自关联 ...

  4. django的Model 模型中常用的字段类型

    常用的字段类型: AutoField:自增长字段,通常不用,如果未在Model中显示指定主键,django会默认建立一个整型的自增长主键字段 BooleanField:布尔型,值为True或False ...

  5. 7.Django模型类的定义和管理

    Django的模型类是给ORM层服务的 1.每个数据模型都是django.db.models.Model的子类. 2.它的父类Model包含了所有必要的和数据库交互的方法,并提供了定义数据库字段的语法 ...

  6. django模型类

    模型类 ORM django中内嵌了ORM框架,ORM框架可以将类和数据表进行对应起来,只需要通过类和对象就可以对数据表进行操作. 在Django中主要是设计类:模型类. ORM另外一个作用:根据设计 ...

  7. Django模型类Meta元数据详解

    转自:https://my.oschina.net/liuyuantao/blog/751337 简介 使用内部的class Meta 定义模型的元数据,例如: from django.db impo ...

  8. Django | 模型类变更后生成迁移文件,报错:You are trying to add a non-nullable field 'BookName' to BookInfo without a default....

    报错: You are trying to add a non-nullable field 'BookName' to BookInfo without a default; we can't do ...

  9. Django中ORM常用字段类型及参数

    常用字段: <1> CharField 字符串字段, 用于较短的字符串. CharField 要求必须有一个参数 maxlength, 用于从数据库层和Django校验层限制该字段所允许的 ...

随机推荐

  1. bzoj4008: [HNOI2015]亚瑟王 dp

    题目链接 https://www.lydsy.com/JudgeOnline/problem.php?id=4008 思路 神仙啊 \(f[i][j]表示第i个点有j次机会(不管成功与否)\) \(f ...

  2. FJUT 毒瘤3(二分 + 最大匹配)题解

    毒瘤3 TimeLimit:1000MS  MemoryLimit:256MB 64-bit integer IO format:%lld   Problem Description 字节跳动有n款产 ...

  3. swagger实战踩坑1

    1.swagger error 有详细的错误信息 自己根据详细信息找问题 2.swagger error 无详细的错误信息 Controller是否重名=>重名,指定不同的   [Route(& ...

  4. Ubuntu 18.04版本下安装网易云音乐

    这是我迄今为止发现的最完美的解决方法,不用改任何东西,只需要安装然后打开即可,后台也有. 参考:http://archive.ubuntukylin.com:10006/ubuntukylin/poo ...

  5. JQGrid 在页面加载时展开SubGrid

    1.jqgrid在加载完成之后展开SubGrid,用得如下办法: gridComplete: function () { var rowIds = $("#list2").getD ...

  6. File操作-将数据库里的数据写入到指定路径的txt文件里

    package com.Cristin.File;//将数据库里的数据写入到指定路径的txt文件里 import java.io.File;import java.io.FileOutputStrea ...

  7. _itemmod_stat

    制作几种基础模板,用模板快速生成装备 `comment` 备注 `entry`目标装备 entry `src_entry` 模板装备entry `stat_muilt` 属性倍率 `mindmg_mu ...

  8. 数据库无法打开到SQL Server连接

    今天打开数据库,发现连接不上,弹出错误提示: 打开SQLServer Configuration Manager,发现SQL Server状态已经停止,双击启动弹出错误提示: 打开SQL Server ...

  9. config配置

    <?php /** * User: Eden * Date: 2019/3/30 * 共有内容 */ /** CREATE TABLE `tf_configs` ( `id` int(11) N ...

  10. 使用cmd命令进行导入

    进入cmd直接输入命令 imp 用户名/密码@监听器路径/数据库实例名称 file='d:\数据库文件.dmp' full=y ignore=y 例如: imp mislogin/mislogin@l ...