python的Web框架,Django模型系统二,模型属性,及数据库进阶查询

<h6 id="原始数据接上篇文章来操作-可能需要查看后才能懂" data-source-line="1">原始数据接上篇文章来操作。可能需要查看后才能懂。<a href="https://www.cnblogs.com/hua888/p/10442702.html" target="_blank">点击这里查看

<h3 id="django和mysql的对应类型modelsmodel下的方法" data-source-line="8">django和mysql的对应类型,models.Model下的方法


<table data-source-line="9">

django类型 映射到mysql类型 <h1 id="2字段的常用参数" data-source-line="21">2.字段的常用参数
<p data-source-line="22">官方文档:<a href="https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-options" target="_blank">https://docs.djangoproject.com/en/2.1/ref/models/fields/#field-options


<h3 id="field常用参数" data-source-line="23">field常用参数
<table data-source-line="24">

参数名 作用
= models.IntegerField(primary_key=True,auto_created=第二种方式:使用AutoField方法,这个方法是自增长且为int类型
id
= models.AutoField(primary_key=True使用AutoField方法,这个方法是自增长且为int类型)

<h5 id="unique设置唯一注意的事项" data-source-line="42">unique设置唯一,注意的事项
<div class="cnblogs_code">

 qq = models.CharField(max_length=20,,null=True)

<h1 id="3常用查询" data-source-line="52">3.常用查询
<h4 id="管理器理解" data-source-line="54">管理器理解
<p data-source-line="55">objects是Students的对象,是django.db.models.manager.Manager的一个实例。


<div class="cnblogs_code">

>>>

<h4 id="queryset" data-source-line="60">QuerySet
<p data-source-line="61">表示数据库中对象的集合,可以等同于select的语句。它是惰性的。

<h2 id="单条数据查询" data-source-line="65">单条数据查询:
<p data-source-line="67">排序:默认按照主键id排序,可以通过模型中的_meta属性设置排序问题。


<h4 id="first-获取第一条返回的是一个对象默认按照主键id排序" data-source-line="69">
<span style="font-size: 18px;">first 获取第一条,返回的是一个对象,默认按照主键id排序
<div class="cnblogs_code">

>>>

<h4 id="last-获取最后一条默认按照主键id排序" data-source-line="75">
<span style="font-size: 18px;">last 获取最后一条,默认按照主键id排序
<div class="cnblogs_code">

>>>

<h4 id="getkwargs-根据给定的条件获取一个对象如果有多个对象符合则会报错" data-source-line="81">
<span style="font-size: 18px;">get(**kwargs) 根据给定的条件,获取一个对象,如果有多个对象符合,则会报错。
<div class="cnblogs_code">

>>>Students.objects.get(name=

<h2 id="多条数据查询" data-source-line="89">多条数据查询
<h4 id="all-获取所有记录返回的是queryset" data-source-line="91">all() 获取所有记录,返回的是QuerySet
<div class="cnblogs_code">

>>>,,,,,,,,,]>

<h4 id="filterkwargs过滤根据给定的条件获取一个过滤后的queryset多个条件的queryset语句是and连接" data-source-line="97">
<span style="font-size: 18px;">filter(**kwargs):过滤,根据给定的条件,获取一个过滤后的QuerySet,多个条件的QuerySet语句是and连接
<div class="cnblogs_code">

>>>res = Students.objects.filter(sex=1,age=16>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.name,teacher_students.age,teacher_students.sex,teacher_students.qq,teacher_students.phone,teacher_students.c_time FROM teacher_students WHERE (teacher_students.age = 16 AND teacher_students.sex = 1)

<h4 id="excludekwargs-排除和filter使用方法一致作用相反根据给定的条件获取一个排除后的queryset可以多个条件" data-source-line="105">
<span style="font-size: 18px;">exclude(**kwargs) 排除,和filter使用方法一致,作用相反,根据给定的条件,获取一个排除后的QuerySet,可以多个条件
<div class="cnblogs_code">

>>>res = Students.objects.exclude(sex=1>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE NOT (teacher_students.sex = 1)

<h4 id="q或者多条件查询相当于mysql中的or这个方法需要单独导入" data-source-line="113">Q:或者,多条件查询,相当于MySQL中的or,这个方法需要单独导入
<p data-source-line="114">需要导包


<div class="cnblogs_code">

 django.db.models  Q

<p data-source-line="118">语法: Q(*args) |


<div class="cnblogs_code">

>>> res =Students.objects.filter(Q(age=0)|Q(age=1= 0 OR `teacher_students`.`age` = 1)

<h4 id="valuesfields字段查询-可以多个查询返回一个queryset返回一个字典列表而不是数据对象" data-source-line="124">
<span style="font-size: 18px;">values(*fields),字段查询。可以多个查询,返回一个QuerySet,返回一个字典列表,而不是数据对象
<div class="cnblogs_code">

>>> res = Students.objects.values(>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.name FROM teacher_students

>>><span style="color: #000000;">res
<QuerySet [{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">小明<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">XiaoHong<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">王五<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">赵柳<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">张三<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">李思<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">孙奇<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">ABC<span style="color: #800000;">'},{<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">': <span style="color: #800000;">'<span style="color: #800000;">abc<span style="color: #800000;">'},{>

res[0][<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">'<span style="color: #000000;">]
<span style="color: #800000;">'<span style="color: #800000;">小明<span style="color: #800000;">'
<span style="color: #008000;">#<span style="color: #008000;">可以多条查询 res = Students.objects.values('name','age') <span style="color: #008000;">

<span style="color: #008000;">可以增加过滤 res = Students.objects.values('name').filter(age=0)

<h4 id="onlyfield-返回queryset是一个对象列表不是字典而且only一定包含主键字段-此方法用的更多些" data-source-line="140">
<span style="font-size: 18px;">only(*field) 返回QuerySet,是一个对象列表,不是字典,而且only一定包含主键字段。此方法用的更多些。
<p data-source-line="141">因为是一个对象列表,所以可以有后期的其他操作,我们可以指定很少的字段后再后期继续获取,效率较高,还可以动态的拿到其他数据。


<div class="cnblogs_code">

>>> res = Students.objects.only(>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.name FROM teacher_students
<span style="color: #008000;">#
<span style="color: #008000;">会默认拿到id主键

<span style="color: #000000;">res[0].c_time
datetime.datetime(2019,2,26,8,4,57,955584,tzinfo=<span style="color: #000000;">)
<span style="color: #008000;">#<span style="color: #008000;">没有获取这个字段也一样可以拿到,这就是only的作用

<span style="color: #008000;">#<span style="color: #008000;">其他写法:
res = Students.objects.only(<span style="color: #800000;">'<span style="color: #800000;">name<span style="color: #800000;">',<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">').filter(age=16)

<h4 id="deferfields-返回一个queryset和only一样用法作用相反" data-source-line="156">
<span style="font-size: 18px;">defer(*fields) 返回一个QuerySet,和only一样用法,作用相反
<div class="cnblogs_code">

>>>res = Students.objects.defer(,>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.phone FROM teacher_students

>>><span style="color: #000000;">res
<QuerySet [<Students: 小明-16>,,<Students: 刘一-19>]>

<span style="color: #000000;">res[0].c_time
datetime.datetime(2019,tzinfo=)

<h2 id="排序" data-source-line="169">排序
<h4 id="order_byfields根据给定的字段来排序默认是正序在字段名前加上-会变成反序可以多字段排序" data-source-line="171">
<span style="font-size: 18px;">order_by(*fields):根据给定的字段来排序,默认是正序,在字段名前加上-,会变成反序,可以多字段排序。
<p data-source-line="172">正序


<div class="cnblogs_code">

>>>res = Students.objects.order_by(>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students ORDER BY teacher_students.c_time ASC

<span style="color: #008000;">#<span style="color: #008000;">可以配合only使用:<span style="color: #008000;">

<span style="color: #008000;">res = Students.objects.order_by('c_time').only('name')

<p data-source-line="182">反序,在需要的条件前面加上'-'


<div class="cnblogs_code">

>>>res = Students.objects.order_by(>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students ORDER BY teacher_students.c_time DESC

<h4 id="lower按照小写进行排序创建复杂查询的时候用" data-source-line="189">
<span style="font-size: 14pt;">Lower:按照小写进行排序,创建复杂查询的时候用。
<p data-source-line="190">Lower这个方法需要导包


<div class="cnblogs_code">

 django.db.models.functions  Lower

<p data-source-line="194">正序


<div class="cnblogs_code">

>>> res = Students.objects.order_by(Lower(>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students ORDER BY LOWER(teacher_students.name) ASC
<span style="color: #008000;">#
<span style="color: #008000;">LOWER是数据库本身的功能,它把字段的内容(teacher_students.name) 变成大写排序。

<span style="color: #000000;"> res
<QuerySet [,,<Students: 刘一-19>,<Students: 小明-16>,<Students: 王五ents: 赵柳-22>,<Students: 赵柳-19>]>

<p data-source-line="205">倒序


<div class="cnblogs_code">

>>> res = Students.objects.order_by(Lower(>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students ORDER BY LOWER(teacher_students.name) DESC

>>><span style="color: #000000;"> res
<QuerySet [<Students: 赵柳-22>,,]>

<h2 id="切片" data-source-line="215">切片
<h4 id="等同于mysql里面的limitoffset数量量和偏移量和python的列表切片用法相似不支持负索引数量量大时不用步长" data-source-line="216">等同于MySQL里面的LIMIT,OFFSET,数量量和偏移量,和python的列表切片用法相似,不支持负索引,数量量大时不用步长
<h4 id="切片过后不再支持附加的过滤条件与排序条件需要放在切片之前" data-source-line="217"><span style="text-decoration: underline;"><span style="font-size: 16px;">***切片过后,不再支持附加的过滤条件与排序,条件需要放在切片之前。
<div class="cnblogs_code">

>>>res = Students.objects.all()[:5>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students LIMIT 5

res = Students.objects.all()[2:6<span style="color: #000000;">]

>>><span style="color: #0000ff;">print(res.query) <span style="color: #008000;">#<span style="color: #008000;">打印出他的sql语句
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students LIMIT 4 OFFSET 2

res = Students.objects.all()[::2<span style="color: #000000;">]

>>><span style="color: #000000;">res
[<Students: 小明-16>,<span style="color: #000000;">]
<span style="color: #008000;">#<span style="color: #008000;">得到的直接是一个list列表,不是一个对象,不能再有后续的操作

<h2 id="常用查询条件-一般使用双下划线-" data-source-line="239">常用查询条件 ,一般使用双下划线 '<span style="color: #ff0000;">'
<h6 id="支持filter-exclude-get-link子句" data-source-line="240"><span style="font-size: 16px;">支持 filter、exclude、get……,LINK子句
<h4 id="exact精准匹配对象列表" data-source-line="241">
<span style="font-size: 18px;">exact:精准匹配,对象列表
<div class="cnblogs_code">

>>> res = Students.objects.filter(id__exact=4

<span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.id = 4

<h4 id="iexact不区分大小写对象列表" data-source-line="249">
<span style="font-size: 18px;">iexact:不区分大小写,对象列表
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__iexact=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE abc

>>><span style="color: #000000;"> res
<QuerySet [,]>

<h4 id="contains-包含" data-source-line="259">
<span style="font-size: 18px;">contains 包含
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__contains=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE BINARY
%abc%

<span style="color: #000000;"> res
<QuerySet []>

<h4 id="icontains-包含不区分大小写" data-source-line="269">
<span style="font-size: 18px;">icontains 包含,不区分大小写
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__icontains=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE
%abc%

<h4 id="in在里面找" data-source-line="278">
<span style="font-size: 18px;">in:在……里面找
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__in=[,,>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name IN (abc,ABC,小明)

<h4 id="range范围在一个范围内找" data-source-line="286">
<span style="font-size: 18px;">range:范围,在一个范围内找。
<div class="cnblogs_code">

>>> res = Students.objects.filter(age__range=(14,20>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.age BETWEEN 14 AND 20

<span style="color: #000000;"> res
<QuerySet [<Students: 小明-16>,<Students: 刘一-19>]>

<h4 id="ge大于gee大于等于" data-source-line="297">
<span style="font-size: 18px;">gt:大于,<span style="font-size: 18px;">gte:大于等于
<div class="cnblogs_code">


>>> res = Students.objects.filter(age__gt=18>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.age
> 18

<span style="color: #008000;">#<span style="color: #008000;">大于等于 方法

res = Students.objects.filter(age__gte=18<span style="color: #000000;">)

>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.age >= 18

<h4 id="lt小于lte小于等于" data-source-line="314">
<span style="font-size: 18px;">lt:小于,<span style="font-size: 18px;">lte:小于等于
<div class="cnblogs_code">


>>> res = Students.objects.filter(age__lt=18>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.age
< 18

<span style="color: #008000;">#<span style="color: #008000;">小于等于 方法

res = Students.objects.filter(age__lte=18<span style="color: #000000;">)

>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.age <= 18

<h4 id="startswith-以开头大小写敏感区分大小写" data-source-line="331">
<span style="font-size: 18px;">startswith :以……开头,大小写敏感,区分大小写
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__startswith=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE BINARY 小
%

<h4 id="istartswith-以开头不区分大小写" data-source-line="338">
<span style="font-size: 18px;">istartswith :以……开头,不区分大小写
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__istartswith=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE 小
%

<h4 id="endswith-以结尾区分大小写" data-source-line="345">
<span style="font-size: 18px;">endswith :以……结尾,区分大小写
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__endswith=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE BINARY
%小

<h4 id="iendswith-以结尾不区分大小写" data-source-line="353">
<span style="font-size: 18px;">iendswith :以……结尾,不区分大小写
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__iendswith=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name LIKE
%小

<h4 id="isnull返回truefalsebool值对应mysql中的is-null-is-not-null" data-source-line="362">
<span style="font-size: 18px;">isnull:返回True,False,BOOL值,对应MySQL中的IS NULL、IS NOT NULL
<h5 id="truefalse-做-if-nullif-not-null-查" data-source-line="363">True/False; 做 IF NULL/IF NOT NULL 查
<div class="cnblogs_code">

>>> res = Students.objects.filter(name__isnull=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name IS NULL

>>> res = Students.objects.filter(name__isnull=<span style="color: #000000;">False)

>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time FROM teacher_students WHERE teacher_students.name IS NOT NULL

<h4 id="快速查找方法表" data-source-line="376">快速查找方法表
<table data-source-line="377">

类型 描述 startswith <h2 id="聚合" data-source-line="401">聚合
<p data-source-line="402">需要导包


<div class="cnblogs_code">

 django.db.models  Count,Avg,Max,Min,Sum

<p data-source-line="406">通过管理器的aggregate方法


<h4 id="count-统计与count首字母小写" data-source-line="408">
<span style="font-size: 18px;">Count
统计与<span style="font-size: 18px;">count(首字母小写)
<div class="cnblogs_code">

>>> Students.objects.filter(name__startswith=1大写Count
>>> Students.objects.filter(sex=1).aggregate(age_count=Count(<span style="color: #800000;">'
<span style="color: #800000;">age
<span style="color: #800000;">'
<span style="color: #000000;">))
{
<span style="color: #800000;">'
<span style="color: #800000;">age_count<span style="color: #800000;">': 7}

平均数

>>> Students.objects.filter(sex=1).aggregate(age_avg=Avg(: 17.4286}

<h4 id="max-最大" data-source-line="427">
<span style="font-size: 18px;">Max 最大
<div class="cnblogs_code">

>>> Students.objects.filter(sex=1).aggregate(age_max=Max(: 29}

<h4 id="min-最小" data-source-line="433">
<span style="font-size: 18px;">Min 最小
<div class="cnblogs_code">

>>> Students.objects.filter(sex=1).aggregate(age_min=Min(: 5}

<h4 id="求和" data-source-line="438">
<span style="font-size: 18px;">Sum 求和
<div class="cnblogs_code">

>>> Students.objects.filter(sex=1).aggregate(age_sum=Sum(: 122}

<h2 id="分组" data-source-line="445">分组
<h5 id="需要配合聚合-values-count一起使用" data-source-line="446">需要配合聚合、values、Count一起使用
<p data-source-line="447">通过找到字段数据后,然后对这个字段的信息进行聚合后,再分组


<div class="cnblogs_code">

>>> Students.objects.values().annotate(num=Count(: 1,: 7},{: 0,: 4}]>

Students.objects.values(<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">').annotate(num=Count(<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">'<span style="color: #000000;">))
<QuerySet [{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 16,<span style="color: #800000;">'<span style="color: #800000;">num<span style="color: #800000;">': 2},{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 24,<span style="color: #800000;">'<span style="color: #800000;">num<span style="color: #800000;">': 1},{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 22,{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 23,{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 17,{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 19,{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 29,{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 5,{<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">': 6,<span style="color: #800000;">'<span style="color: #800000;">num<span style="color: #800000;">': 1}]>

res = Students.objects.values(<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">').annotate(num=Count(<span style="color: #800000;">'<span style="color: #800000;">age<span style="color: #800000;">'<span style="color: #000000;">))

>>><span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.age,COUNT(teacher_students.age) AS num FROM teacher_students GROUP BY teacher_students.age ORDER BY NULL

<h1 id="4表关系的实现" data-source-line="466">4.表关系的实现
<p data-source-line="467">

<img src="https://www.jb51.cc/res/2019/03-02/09/311aed8bb3a039c30589472533570b59.png" alt="">


<h1 id="mysql表关系的创建在django中创建模型来生成mysql中表的关系" data-source-line="1">MySQL表关系的创建:在Django中创建模型来生成MySQL中表的关系。
<h3 id="onetoone一对一的表关系onetoonefield方法" data-source-line="3">
<span style="font-size: 18px;">OneToOne:一对一的表关系,OneToOneField方法
<p data-source-line="4">使用主键关联主键。模型类操作。


<pre data-source-line="6"><code class="hljs"><span class="zh-hans">例子如上面内容所写
<div class="cnblogs_code">

  django.db  
               name = models.CharField(max_length=20         age = models.SmallIntegerField(default=         sex = models.SmallIntegerField(default=1         qq = models.CharField(max_length=20,unique=True,null=         phone = models.CharField(max_length=20,null=         c_time = models.DateTimeField(verbose_name=,auto_now_add=         e_time = models.DateTimeField(verbose_name=,auto_now=     
         
                         % 
           num = models.CharField(max_length=20,default=         college = models.CharField(max_length=20,default=         student = models.OneToOneField(,on_delete=         
         
         一对一的关联操作解析:
         student = models.OneToOneField(,on_delete=         第一个参数是需要关联的表,需要字符串操作,第二个参数表示级联操作,如果主表有信息删除则此表信息也会跟着删除。

<h3 id="onetomany一对多的表关系foreignkey方法" data-source-line="38">
<span style="font-size: 18px;">OneToMany:一对多的表关系,ForeignKey方法
<div class="cnblogs_code">

 django.db 学生主表(多)
</span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Students(models.Model):
    name </span>= models.CharField(max_length=20<span style="color: #000000;"&gt;)
    age </span>= models.SmallIntegerField(default=<span style="color: #000000;"&gt;0)
    sex </span>= models.SmallIntegerField(default=1<span style="color: #000000;"&gt;)
    qq </span>= models.CharField(max_length=20,null=<span style="color: #000000;"&gt;True)
    phone </span>= models.CharField(max_length=20,null=<span style="color: #000000;"&gt;True)
    c_time </span>= models.DateTimeField(verbose_name=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;创建时间</span><span style="color: #800000;"&gt;'</span>,auto_now_add=<span style="color: #000000;"&gt;True)
    e_time </span>= models.DateTimeField(verbose_name=<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;编辑时间</span><span style="color: #800000;"&gt;'</span>,auto_now=<span style="color: #000000;"&gt;True)
    grade </span>= models.ForeignKey(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Grade</span><span style="color: #800000;"&gt;'</span>,on_delete=models.SET_NULL,null=<span style="color: #000000;"&gt;True)


    多对一关联解析:</span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;ForeignKey</span><span style="color: #800000;"&gt;'</span><span style="color: #000000;"&gt;:设置外键关联Grade表
    grade </span>= models.ForeignKey(<span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;Grade</span><span style="color: #800000;"&gt;'</span>,null=<span style="color: #000000;"&gt;True)
    </span><span style="color: #800000;"&gt;'</span><span style="color: #800000;"&gt;on_delete=models.SET_NULL</span><span style="color: #800000;"&gt;'</span>:(必须带一个null=<span style="color: #000000;"&gt;True)代表如果关联的表对应数据被删除,则显示NULL,不会被级联删除(如果班级被删除,学生则还在,所以不能级联)

班级表(一)
</span><span style="color: #0000ff;"&gt;class</span><span style="color: #000000;"&gt; Grade(models.Model):
    num </span>= models.CharField(max_length=20<span style="color: #000000;"&gt;)
    name </span>= models.CharField(max_length=20)</pre>

<h3 id="manytomany多对多的表关系manytomanyfield" data-source-line="64">
<span style="font-size: 18px;">ManyToMany:多对多的表关系,ManyToManyField
<h5 id="只有一个字段的多对多简单的多对多" data-source-line="66">只有一个字段的多对多:(简单的多对多)
<div class="cnblogs_code">

  django.db  
               name = models.CharField(max_length=20         age = models.SmallIntegerField(default=         sex = models.SmallIntegerField(default=1         qq = models.CharField(max_length=20,auto_now=         grade = models.ForeignKey(,null=         
         
               name = models.CharField(,max_length=20         students = models.ManyToManyField( 
 

<h5 id="多张表的多对多复杂通过manytomany多对多表和foreignkey外键来实现" data-source-line="89">多张表的多对多,复杂,通过ManyToMany(多对多表)和ForeignKey(外键)来实现。
<div class="cnblogs_code">

  django.db  
               name = models.CharField(max_length=20         age = models.SmallIntegerField(default=         sex = models.SmallIntegerField(default=1         qq = models.CharField(max_length=20,max_length=20         students = models.ManyToManyField(,through=         
               student = models.ForeignKey(,on_delete=         student = models.ForeignKey(,on_delete=         pay = models.IntegerField(,default=         c_time = models.DateTimeField(,auto_now_add=True)

<p data-source-line="117">使用报名表的两个外键把学生表和报名表关联起来,来达到多对多的方法,但是想要学生表直接访问到课程表,就需要在ManyToMany的参数中设置好两张表的关联。('多对多的表',through=来源的表)


<p data-source-line="117"> 


<p data-source-line="117"> 


<p data-source-line="117">创建关系的5张表汇总代码如下。


<div class="cnblogs_code">

   django.db  
 
 
 
      name = models.CharField(max_length=20     age = models.SmallIntegerField(default=     sex = models.SmallIntegerField(default=1     qq = models.CharField(max_length=20,null=     phone = models.CharField(max_length=20,null=     c_time = models.DateTimeField(verbose_name=,auto_now_add=     e_time = models.DateTimeField(verbose_name=,auto_now=     grade = models.ForeignKey(,null= 
                 % 
 
 
      num = models.CharField(max_length=20,default=     college = models.CharField(max_length=20,default= 
     
     student = models.OneToOneField(,on_delete= 
 
 
      num = models.CharField(max_length=20     name = models.CharField(max_length=20 
 
 
      name = models.CharField(max_length=20     student = models.ManyToManyField(,through= 
 
 
      student = models.ForeignKey(,on_delete=     course = models.ForeignKey(,on_delete=     pay = models.IntegerField(,default=     c_time = models.DateTimeField(,auto_now_add=True)

<h5 id="输出的结果通过工具查看他的导向图" data-source-line="172">输出的结果通过工具查看他的导向图:
<p data-source-line="173">

<img src="https://www.jb51.cc/res/2019/03-02/09/52acea51d6d86788c2f08813f6f7ed33.png" alt="">

<p data-source-line="175">sqlmigrate 从迁移获取sql语句:获取创建表的sql语句


<div class="cnblogs_code">

>>> python manage.py sqlmigrate teacher 0001解析: teacher:appname        0001:Django的迁移执行文件

<table data-source-line="181">

参数 作用 <h1 id="关联表的数据操作" data-source-line="189">关联表的数据操作
<h2 id="one-to-many一对多and多对一" data-source-line="190">One-To-Many:一对多and多对一
<h3 id="正向的增删改查" data-source-line="191">正向的增删改查:
<p data-source-line="192">一个模型如果定义了一个外键字段,通过这个模型的操作外键就是正向。


<p data-source-line="194">现在我们开始操作数据库:


<p data-source-line="196">首先给年级表teacher_grade表增加几条数据


<table data-source-line="197">

id num name

<span style="color: #008000;">#<span style="color: #008000;"> 先拿到Grade的一条数据

g1 =<span style="color: #000000;"> Grade.objects.first()

<span style="color: #008000;">#<span style="color: #008000;"> 获取一个Students的空对象

s =<span style="color: #000000;"> Students()

<span style="color: #008000;">#<span style="color: #008000;"> 给对象添加一个name字段的数据

s.name = <span style="color: #800000;">'<span style="color: #800000;">张三<span style="color: #800000;">'

<span style="color: #008000;">#<span style="color: #008000;"> 把g1的数据复制给Students的grade的字段,然后得到数据。

s.grade =<span style="color: #000000;"> g1

<span style="color: #008000;">#<span style="color: #008000;"> 保存

s.save()

<p data-source-line="222">第二种方法:通过外键字段得到关联表的数据,用对象的外键字段名接受关联表的数据(id获取)


<div class="cnblogs_code">

>>> s2 = Students(name=>>> g2 =<span style="color: #000000;"> Grade.objects.last()

<span style="color: #008000;">#<span style="color: #008000;"> 用对象的外键字段名接受关联表的数据,需要是关联表的主键id

s2.grade_id =<span style="color: #000000;"> g2.id

>> sa.save()

<h4 id="更新和修改" data-source-line="233">更新和修改


<p data-source-line="234">也可以通过赋值来操作


<div class="cnblogs_code">


>>> s.grade =>>> s.save()

<h4 id="删除外键数据" data-source-line="241">删除外键数据
<div class="cnblogs_code">


>>> s.grade =>>> s.save()

<h3 id="查询" data-source-line="250">查询
<div class="cnblogs_code">


>>>

<h3 id="反向的增删改查" data-source-line="257">反向的增删改查
<p data-source-line="258">一个模型被另外一个模型的外键关联,通过这个模型对关联他的这个模型操作就是反向。


<h5 id="通过被关联表名的小写加上set来操作-管理器范式小写_set" data-source-line="259">通过被关联表名的小写加上set来操作。管理器范式(小写_set)
<h4 id="增加" data-source-line="261">增加
<div class="cnblogs_code">


>>> g2.students_set.create(name=

<span style="color: #008000;">#<span style="color: #008000;">把已有的对象通过add方法增加关联的数据,此方法立刻执行,如果本身自带了数据,则自动修改为本对象的数据

g2.students_set.add(s)

<h4 id="查询-2" data-source-line="270">查询
<div class="cnblogs_code">

>>>,,]>

<span style="color: #008000;">#<span style="color: #008000;">查询的所有方法都可以使用,这里只做一个例子

<h4 id="删除" data-source-line="277">删除
<div class="cnblogs_code">


>>><span style="color: #008000;">#<span style="color: #008000;">删除所有

g2.students_set.clear()

<h4 id="set方法接受对象列表此方法是先执行clear后再执行set添加" data-source-line="285">
<span style="font-size: 18px;">set方法,接受对象列表,此方法是先执行<span style="font-size: 16px; color: #ff0000;">clear后,再执行<span style="font-size: 18px; color: #ff0000;">set添加。
<p data-source-line="286">把本来有的对象删除后,再添加新的对象


<div class="cnblogs_code">


>>>>>> g3.students_set.all()

<h5 id="通过本表的外键查询关联表的关于本表的数据" data-source-line="293">通过本表的外键查询关联表的关于本表的数据
<p data-source-line="294">通过学生表查询年级表的所有学生,用外键字段加上__和关联表的字段名,字段查询,不能全部查询


<div class="cnblogs_code">


res = Students.objects.filter(grade__name=<span style="color: #800000;">'<span style="color: #800000;">爬虫<span style="color: #800000;">'<span style="color: #000000;">)

>>><span style="color: #000000;"> res
<QuerySet [<Students: 张三-0>,<Students: 赵柳-0>]>

<span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.c_time,teacher_students.e_time,teacher_students.grade_id FROM teacher_students INNER JOIN teacher_grade ON (teacher_students.grade_id = teacher_grade.id) WHERE teacher_grade.name = 爬虫

<h2 id="many-to-many多对多" data-source-line="308">Many-To-Many:多对多
<p data-source-line="309">多对多的两端都可以获得自动API去访问,访问的原理和一对多的反向有点类似,但是有一个不同的地方是多对多的模型使用的是本字段的属性名,而反向的是使用原始模型的小写加上set。下面我们来看怎么操作。


<h5 id="指定了中间表后add-remove-set都不能用必须用中间表" data-source-line="311">指定了中间表后,add、remove、set都不能用,必须用中间表。
<p data-source-line="312">首先增加几个课程数据(Course)来实现例子:


<table data-source-line="313">

id name id add、remove、set都是没有指定中间表(through='Enroll')的时候才可以使用,不能使用用在对多的字段,当他指定这个的时候,就不能使用。

>>> c1,c3 =<span style="color: #008000;">#<span style="color: #008000;"> 把创建出来的Students对象获取到变量中得到s1,s2,s3

s1,s3 = Students.objects.all()

<h4 id="增加-2" data-source-line="335">增加
<div class="cnblogs_code">


>>> e =<span style="color: #008000;">#<span style="color: #008000;"> 把c1的对象赋值给Enroll的这个对象

e.course =<span style="color: #000000;"> c1

<span style="color: #008000;">#<span style="color: #008000;"> 把s1的对象赋值给Enroll的这个对象

e.student =<span style="color: #000000;"> s1

>>><span style="color: #000000;"> e.save()

<span style="color: #008000;">#<span style="color: #008000;">用两个外键字段名接受 关联表对象的数据。然后保存,可以得到一条外键关联的数据。

<p data-source-line="350">结果得到的Enroll表数据为:


<table data-source-line="351">

id >>> e.course_id =>>> e.student_id =<span style="color: #000000;"> s2.id

>>> e.save()

<p data-source-line="363">结果到的Enroll表为:


<table data-source-line="364">

id
>>> Enroll.objects.create(sudent=s1,course=c3)

<h4 id="表中manytomany方法的应用" data-source-line="374">表中ManyToMany方法的应用。
<div class="cnblogs_code">


student = models.ManyToManyField(,through=

<p data-source-line="379">我们来应用这个管理器,他可以很方便的查询到我们需要的数据,不是一个字段,我们可以在不使用第三张表(Enroll表)介入的时候,让Students和Course两个相互访问。


<div class="cnblogs_code">


>>>.ManyRelatedManager at 0xaff763ec>

<span style="color: #008000;">#<span style="color: #008000;"> 查找c1下面的所有学生

<span style="color: #000000;"> c1.student.all()
<QuerySet [<Students: 张三-0>]>

<span style="color: #008000;">#<span style="color: #008000;"> 查找学生报名的所有课程

<span style="color: #000000;"> s1.course_set.all()
<QuerySet [<Course: pyton全栈>]>

<h2 id="one-to-one-一对一" data-source-line="393">One-To-One 一对一
<h5 id="增加-3" data-source-line="394">增加
<div class="cnblogs_code">

>>> sd = StudentsDetail.objects.create(num=,college=,student=>>><span style="color: #000000;"> sd
<StudentsDetail: 家里蹲-20190301001>

<h5 id="查询-3" data-source-line="401">查询
<div class="cnblogs_code">

>>>

<span style="color: #000000;"> sd.student.name
<span style="color: #800000;">'<span style="color: #800000;">张三<span style="color: #800000;">'

<p data-source-line="409">在一对一的关系中,可以通过关联表的模型名的小写(是对象,不是管理器),来拿到需要的数据,没有_set


<div class="cnblogs_code">

>>>

<span style="color: #000000;"> s1.studentsdetail.num
<span style="color: #800000;">'<span style="color: #800000;">20190301001<span style="color: #800000;">'

<h2 id="跨表查询" data-source-line="417">跨表查询
<p data-source-line="418">跨模型的相关字段的字段名,并且用双下划綫'__'去分割,直到达到想要获取的字段位置。


<h5 id="例子" data-source-line="420"><span style="font-size: 16px;">通过例子来查看如何跨表查询
<p data-source-line="421">查询男生都报名了什么课程:


<div class="cnblogs_code">


>>> res = Course.objects.filter(student__sex=1>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_course.id,teacher_course.name FROM teacher_course INNER JOIN teacher_enroll ON (teacher_course.id
= teacher_enroll.course_id) INNER JOIN teacher_students ON (teacher_enroll.student_id = teacher_students.id) WHERE teacher_students.sex = 1

<h5 id="反向查询用对应的模型名的小写" data-source-line="430"><span style="font-size: 16px;">反向查询:用对应的模型名的小写。
<p data-source-line="431">查询所有报名python课程的学员:


<div class="cnblogs_code">


res = Students.objects.filter(coursenamecontains=<span style="color: #800000;">'<span style="color: #800000;">python<span style="color: #800000;">'<span style="color: #000000;">)

>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.grade_id FROM teacher_students INNER JOIN teacher_enroll ON (teacher_students.id = teacher_enroll.student_id) INNER JOIN teacher_course ON (teacher_enroll.course_id = teacher_course.id) WHERE teacher_course.name LIKE BINARY %python%

<pre data-source-line="432"><span style="font-size: 16px;">and关系
<p data-source-line="441">查询所有报名英语的33期的学员:


<div class="cnblogs_code">

>>> res = Students.objects.filter(course__name__contains=,grade__num__contains=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.grade_id FROM teacher_students INNER JOIN teacher_enroll ON (teacher_students.id
= teacher_enroll.student_id) INNER JOIN teacher_course ON (teacher_enroll.course_id = teacher_course.id) INNER JOIN teacher_grade ON (teacher_students.grade_id = teacher_grade.id) WHERE (teacher_course.name LIKE BINARY %englist% AND teacher_grade.num LIKE BINARY %33期%)

<pre data-source-line="443">查询所有缴费金额小于3000的学员:
<div class="cnblogs_code">

>>> res = Students.objects.filter(enroll__pay__lt=3000>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_students.id,teacher_students.grade_id FROM teacher_students INNER JOIN teacher_enroll ON (teacher_students.id = teacher_enroll.student_id) WHERE teacher_enroll.pay < 3000.0

<pre data-source-line="450">查询所有报名python的班级有哪些
<div class="cnblogs_code">

>>> res = Grade.objects.filter(students__course__name__contains=>>> <span style="color: #0000ff;">print<span style="color: #000000;">(res.query)
SELECT teacher_grade.id,teacher_grade.num,teacher_grade.name FROM teacher_grade INNER JOIN teacher_students ON (teacher_grade.id
= teacher_students.grade_id) INNER JOIN teacher_enroll ON (teacher_students.id = teacher_enroll.student_id) INNER JOIN teacher_course ON (teacher_enroll.course_id = teacher_course.id) WHERE teacher_course.name LIKE BINARY %python%

<pre data-source-line="457"><span style="color: #ff0000;"><span style="font-size: 18px;">跨表查询小节:需要查询的结果表名放在前面,然后把要查询的内容放在括号内。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


注:所有源代码均实测运行过。所有源代码均已上传CSDN,请有需要的朋友自行下载。
继承APIView和ViewSetMixin;作用也与APIView基本类似,提供了身份认证、权限校验、流量管理等。ViewSet在开发接口中不经常用。
一、Django介绍Python下有许多款不同的 Web 框架。Django是重量级选手中最有代表性的一位。许多成功的网站和APP都基于Django。Django 是一个开放源代码的 Web 应用框架,由 Python 写成。Django 遵守 BSD 版权,初次发布于 2005 年 7 月, 并于 2008 年 9 月发布了第一个正式版本 1.0 。Django学习线路Django 采用了 MVT 的软件设计模式,即模型(Model),视图(View)和模板(Template)。这个MVT模式并
本文从nginx快速掌握到使用,gunicorn快速掌握到使用,实现小白快速搭建django项目,并对可能出现的报错进行了分析
uniapp微信小程序订阅消息发送服务通知
Django终端打印SQL语句 1 Setting配置: 2 默认python 使用的MysqlDB连接,Python3 支持支持pymysql 所有需要在app里面的__init__加上下面配置:
url: re_path(&#39;authors/$&#39;, views.AuthorView.as_view()), re_path(&#39;book/(?P\d+)/$&#39;, vie
前提 关于html寻找路线: template 如果在各个APP中存在, Django 会优先找全局template 文件下的html文件,如果全局下的template文件没有相关的html Djan
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
from bs4 import BeautifulSoup#kindeditordef kindeditor(request): s = &#39;&#39;&#39; &lt;li&gt;&lt;s
view.py 配置 html 配置
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render
from django.http import JsonResponse JsonResponse 里面代码会加这一个响应头 kwargs.setdefault(&#39;content_type&#
浏览器有一个很重要的概念——同源策略(Same-Origin Policy)。所谓同源是指,域名,协议,端口相同。不同源的客户端脚本(javascript、ActionScript)在没明确授权的情况
自动发送 &gt; 依赖jQuery文件 实例--&gt;GET请求: 手动发送 &gt; 依赖浏览器XML对象(也叫原生ajax) Ajax主要就是使用 【XmlHttpRequest】对象来完成请
#下面两种是基于QuerySet查询 也就是说SQL中用的jion连表的方式查询books = models.UserInfo.objects.all() print(type(books)) &gt
// GET请求request.GET // POST请求request.POST // 处理文件上传请求request.FILES // 处理如checkbox等多选 接受列表request.get
return HttpResponse(&quot;OK&quot;) 返回一个字符串 return redirect(&quot;/index/&quot;) 返回URL return render
name age sex qq phone c_time e_time grade_id
pay c_time course_id student_id
pay c_time course_id student_id