Django8

阅读: 评论:0

Django8

Django8

Django——Molde模块

文章目录

  • Django——Molde模块
    • 六、查询拓展
      • 1. 常用查询方法
        • 1-1 查询所有(all)
        • 1-2 filter查询
        • 1-3 get查询
          • 以上三个共同点
        • 1-4 查询第一条(first)
        • 1-5 查询最后一条(last)
        • 1-6 排除查询(exclude)
        • 1-7 指定字段查询(values)
        • 1-8 指定字段查询2 (only)
        • 1-9 指定字段查询3(defer)
        • 1-10 指定字段排序(order_by)
        • 1-11 多条件查询
      • 2. 常用查询条件
        • 2-1 exact和iexact
        • 2-2 包含匹配(contains)
        • 2-3 指定值(in)
        • 2-4 子查询(icontains)
        • 2-5 范围查询
        • 2-6 聚合分组查询(annotate)
    • 七、常用模型字段类型
      • 1.常用的字段类型映射关系
    • 八、Field的常用参数

本篇接上文,在查询之前,我们将Model进行再次升级,使得更加完善:

Student/models.py

from django.db import models# Create your models here.
class Student(models.Model):name = models.CharField(max_length=20)  # 对应于mysql的varcharage = models.SmallIntegerField(null=True)  # 对应于mysql的smallintsex = models.SmallIntegerField(default=1)  # default是默认值qq = models.CharField(max_length=20, null=True, unique=True)  # qq和电话虽然是数字,但是我们保存一般使用字符串去保存phone = models.CharField(max_length=20, null=True, unique=True)# c_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)  # verbose_name用来给该字段添加说明      auto_now_add=True自动填充当前时间)c_time = models.DateTimeField("创建时间", auto_now_add=True)  # 当然你想完全可以在第一个参数写入名字而省略写verbose_name这个参数名x_time = models.DateTimeField("修改时间", auto_now=True)  # 修改之后自动保存def __str__(self):return "这个学生的名字是:%s,年龄为:%d" % (self.name, self.age)

接下来就是迁移的两步(确定迁移数据,和执行迁移),查看以下我们的数据表:

mysql> desc Student_student;
+--------+-------------+------+-----+---------+----------------+
| Field  | Type        | Null | Key | Default | Extra          |
+--------+-------------+------+-----+---------+----------------+
| id     | int         | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20) | NO   |     | NULL    |                |
| age    | smallint    | YES  |     | NULL    |                |
| sex    | smallint    | NO   |     | NULL    |                |
| qq     | varchar(20) | YES  | UNI | NULL    |                |
| phone  | varchar(20) | YES  | UNI | NULL    |                |
| c_time | datetime(6) | NO   |     | NULL    |                |
| x_time | datetime(6) | NO   |     | NULL    |                |
+--------+-------------+------+-----+---------+----------------+
8 rows in set (0.00 sec)

此时我们是没有数据的,我们可以添加进入一些数据:

In [1]: dels import StudentIn [2]: ate(name="summer", age=20, sex=1, qq="12345678", phone="87654321")
Out[2]: <Student: 这个学生的名字是:summer,年龄为:20>In [3]: ate(name="Summer", age=20, sex=1, qq="123", phone="456")
Out[3]: <Student: 这个学生的名字是:Summer,年龄为:20>In [4]: ate(name="July", age=20, sex=1, qq="1234", phone="567")
Out[4]: <Student: 这个学生的名字是:July,年龄为:20>In [5]: ate(name="April", age=20, sex=1, qq="1212", phone="11567")
Out[5]: <Student: 这个学生的名字是:April,年龄为:20>In [6]: ate(name="马冬梅", age=40, sex=0, qq="6666", phone="7777")
Out[6]: <Student: 这个学生的名字是:马冬梅,年龄为:40>In [7]: ate(name="Moli", age=18, sex=0, qq="5678", phone="71212")
Out[7]: <Student: 这个学生的名字是:Moli,年龄为:18>

六、查询拓展

1. 常用查询方法

1-1 查询所有(all)
In [9]: Student.objects.all()
Out[9]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, <0>, <Student: 这个学生的名字是:April,年龄为:20>, <Student: 这个学生的名字是:马冬梅,年龄为:40>, <Student: 这个学生的名字是:Moli,年龄为:18>]>
1-2 filter查询
In [10]: Student.objects.filter(name="summer")
Out[10]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>]>In [11]: res = Student.objects.filter(name="summer")In [12]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` WHERE `Student_student`.`name` = summer
1-3 get查询
In [14]: (name="moli")
Out[14]: <Student: 这个学生的名字是:Moli,年龄为:18>

注意:get所查询的值必须是唯一的,如果没有或者多个将会报错

以上三个共同点

都是通过objects去实现的----》objects:每个django模型类,都有一个默认的管理器,objects

1-4 查询第一条(first)
In [1]: dels import Student as S  # 重新进入,为了方便将Student模型进行重命名In [2]: S.objects.first()
Out[2]: <Student: 这个学生的名字是:summer,年龄为:20>  # 并且查看到这个方法返回的是一个对象而并不是一个queryset
1-5 查询最后一条(last)
In [3]: S.objects.last()
Out[3]: <Student: 这个学生的名字是:Moli,年龄为:18>
1-6 排除查询(exclude)

为了方便,我们与filter进行比较

In [4]: S.objects.filter(name="april")
Out[4]: <QuerySet [<Student: 这个学生的名字是:April,年龄为:20>]>In [5]: lude(name="april")
Out[5]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, <0>, <Student: 这个学生的名字是:马冬梅,年龄为:40>, <Student: 这个学生的名字是:Moli,年龄为:18>]>

我们看到,exclude正好与filter相反,filter是获取这个值,而exclude是排除这个值

1-7 指定字段查询(values)
In [9]: S.objects.values("name")
Out[9]: <QuerySet [{'name': 'summer'}, {'name': 'Summer'}, {'name': 'July'}, {'name': 'April'}, {'name': '马冬梅'}, {'name': 'Moli'}]>

注意:values能拿到指定查询的字段值,其他的无法获取

In [1]: dels import Student as SIn [2]: res = S.objects.values("name")In [3]: res
Out[3]: <QuerySet [{'name': 'summer'}, {'name': 'Summer'}, {'name': 'July'}, {'name': 'April'}, {'name': '马冬梅'}, {'e': 'Moli'}]>In [4]: res[0]["name"]
Out[4]: 'summer'In [5]: res[0]["sex"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-5-1ed973621d80> in <module>
----> 1 res[0]["sex"]KeyError: 'sex'In [6]: print(res.query)
SELECT `Student_student`.`name` FROM `Student_student`
1-8 指定字段查询2 (only)
In [7]: res = ly("name")In [8]: res
Out[8]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, <Student: 这个学生的名字是:July,年龄为:20>, <Student: 这个学生的名字是:April,年龄为:20>, <Student: 这个学生的名字是:马冬梅,年龄为:40>, <Student: 这个学生的名字是:Moli,年龄为:18>]>In [9]: res[0]["name"]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-27a2df2438b0> in <module>
----> 1 res[0]["name"]TypeError: 'Student' object is not subscriptableIn [10]: res[1].name
Out[10]: 'Summer'In [11]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name` FROM `Student_student`

注:这里返回的对象是一个queryset,因此不能在使用字典的方式获取,得用.。并且这个是可以拿到其他值的。

1-9 指定字段查询3(defer)
In [14]: res = S.objects.defer("name")In [15]: res
Out[15]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, 20>, <Student: 这个学生的名字是:April,年龄为:20>, <Student: 这个学生的名字是:马冬梅,年龄为:40>, <Student: 这个学生的名字是:Moli,年龄为:18>]>In [16]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student`

注:defer与only刚好相反

1-10 指定字段排序(order_by)
In [17]: res = der_by('age')In [18]: res
Out[18]: <QuerySet [<Student: 这个学生的名字是:Moli,年龄为:18>, <Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, <Student: 这个学生的名字是:July,年龄为:20>, <Student: 这个学生的名字是:April,年龄为:20>, <Student: 这个学生的名字是:马冬梅,年龄为:40>]>In [19]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` ORDER BY `Student_student`.`age` ASCIn [20]: res = der_by('-age')In [21]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` ORDER BY `Student_student`.`age` DESC

注:写入的值默认为正序,如果想要倒叙直接在前面加-即可

1-11 多条件查询

此时,你需要导入一个包from dels import Q

In [27]: S.objects.filter(age=20,sex=0)
Out[27]: <QuerySet []>In [28]: S.objects.filter(age=20,sex=1)
Out[28]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, 20>, <Student: 这个学生的名字是:April,年龄为:20>]>In [29]: from dels import QIn [30]: S.objects.filter(Q(sex=0),Q(age=20)|Q(age=18))
Out[30]: <QuerySet [<Student: 这个学生的名字是:Moli,年龄为:18>]>

2. 常用查询条件

查找对象的条件的意思是传给以上方法的一些参数。相当于是SQL语句中的where语句后面的条件,语法为字段名__规则(是连着两个下划线哦)

2-1 exact和iexact
In [31]: res = S.objects.filter(name__exact="summer")In [32]: res
Out[32]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>]>In [33]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` WHERE `Student_student`.`name` = summerIn [34]: res = S.objects.filter(name="summer")In [35]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` WHERE `Student_student`.`name` = summerIn [36]: res = S.objects.filter(name__iexact="summer")In [37]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` WHERE `Student_student`.`name` LIKE summerIn [38]: res
Out[38]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>]>

原生sql里面我们发现,exact和”=“是相同的,而iexact将where语句中的=变成了like

mysql> select * from Student_student where name="summer";
+----+--------+------+-----+----------+----------+----------------------------+----------------------------+
| id | name   | age  | sex | qq       | phone    | c_time                     | x_time                     |
+----+--------+------+-----+----------+----------+----------------------------+----------------------------+
|  5 | summer |   20 |   1 | 12345678 | 87654321 | 2021-01-19 04:19:52.965210 | 2021-01-19 04:19:52.965279 |
|  6 | Summer |   20 |   1 | 123      | 456      | 2021-01-19 04:20:13.082947 | 2021-01-19 04:20:13.082981 |
+----+--------+------+-----+----------+----------+----------------------------+----------------------------+
2 rows in set (0.01 sec)mysql> select * from Student_student where name like "summer";
+----+--------+------+-----+----------+----------+----------------------------+----------------------------+
| id | name   | age  | sex | qq       | phone    | c_time                     | x_time                     |
+----+--------+------+-----+----------+----------+----------------------------+----------------------------+
|  5 | summer |   20 |   1 | 12345678 | 87654321 | 2021-01-19 04:19:52.965210 | 2021-01-19 04:19:52.965279 |
|  6 | Summer |   20 |   1 | 123      | 456      | 2021-01-19 04:20:13.082947 | 2021-01-19 04:20:13.082981 |
+----+--------+------+-----+----------+----------+----------------------------+----------------------------+
2 rows in set (0.00 sec)
2-2 包含匹配(contains)

查找包含某个参数的值

In [39]: res = S.objects.filter(name__contains="l")In [40]: res
Out[40]: <QuerySet [<Student: 这个学生的名字是:July,年龄为:20>, <Student: 这个学生的名字是:April,年龄为:20>, <St]>In [41]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` WHERE `Student_student`.`name` LIKE BINARY %l%In [42]: res = S.objects.filter(name__contains="S")In [43]: res
Out[43]: <QuerySet [<Student: 这个学生的名字是:Summer,年龄为:20>]>

注:上面的是对大小写敏感的,如果要不铭感则需要加一个i

In [44]: res = S.objects.filter(name__icontains="S")In [45]: res
Out[45]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>]>
2-3 指定值(in)
In [46]: S.objects.filter(pk__in=[4,5,6])
Out[46]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>]>In [47]: S.objects.filter(sex__in="01")
Out[47]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, 20>, <Student: 这个学生的名字是:April,年龄为:20>, <Student: 这个学生的名字是:马冬梅,年龄为:40>, <Student: 这个学生的名字是:Moli,年龄为:18>]>

这里你可以指定字符串也可以指定列表和元组

2-4 子查询(icontains)
In [50]: res = S.objects.filter(name__icontains="l").only("name")In [51]: res
Out[51]: <QuerySet [<Student: 这个学生的名字是:July,年龄为:20>, <Student: 这个学生的名字是:April,年龄为:20>, <St]>In [52]: res1 = S.objects.filter(pk__in=res).only("name")In [53]: print(res1.query)
SELECT `Student_student`.`id`, `Student_student`.`name` FROM `Student_student` WHERE `Student_student`.`id` IN (SELECT U0.`id` FROM `Student_student` U0 WHERE U0.`name` LIKE %l%)
2-5 范围查询
  • gt 大于
  • gte 大于等于
  • lt 小于
  • lte 小于等于
  • range
In [54]: S.objects.filter(pk__gt=5)
Out[54]: <QuerySet [<Student: 这个学生的名字是:Summer,年龄为:20>, <Student: 这个学生的名字是:July,年龄为:20>, <S0>, <Student: 这个学生的名字是:马冬梅,年龄为:40>, <Student: 这个学生的名字是:Moli,年龄为:18>]>In [58]: res = S.objects.filter(age__range=(10,20))In [59]: res
Out[59]: <QuerySet [<Student: 这个学生的名字是:summer,年龄为:20>, <Student: 这个学生的名字是:Summer,年龄为:20>, 20>, <Student: 这个学生的名字是:April,年龄为:20>, <Student: 这个学生的名字是:Moli,年龄为:18>]>In [60]: print(res.query)
SELECT `Student_student`.`id`, `Student_student`.`name`, `Student_student`.`age`, `Student_student`.`sex`, `Student_student`.`qq`, `Student_student`.`phone`, `Student_student`.`c_time`, `Student_student`.`x_time` FROM `Student_student` WHERE `Student_student`.`age` BETWEEN 10 AND 20
2-6 聚合分组查询(annotate)

同样需要导入:from dels import Count,Avg,Max,Min,Sum

In [63]: from dels import Count,Avg,Max,Min,SumIn [64]: res =  S.objects.values("sex").annotate(num=Count("sex"))In [65]: res
Out[65]: <QuerySet [{'sex': 1, 'num': 4}, {'sex': 0, 'num': 2}]>In [66]: print(res.query)
SELECT `Student_student`.`sex`, COUNT(`Student_student`.`sex`) AS `num` FROM `Student_student` GROUP BY `Student_student`.`sex` ORDER BY NULL

七、常用模型字段类型

官方地址

1.常用的字段类型映射关系

Mysql中的类型Model中的类型说明
intIntegerField整型
varcahrCharField字符类型,通过max_length指定最大长度
longtxtTextField文本类型
dateDateField日期类型,没有时间。映射到数据库中是date类型,在使用的时候,可以设置DateField.auto_now每次保存对象时,自动设置该字段为当前时间
datetimeDateTimeField日期时间类型。映射到数据库中的是datetime类型,在使用的时候,传递datetime.datetime()进去。

八、Field的常用参数

官方文档

  • primary_key: 指定是否为主键。
  • unique: 指定是否唯一。
  • null: 指定是否为空,默认为False。
  • blank: 等于True时form表单验证时可以为空,默认为False。
  • default: 设置默认值。
  • DateField.auto_now: 每次修改都会将当前时间更新进去,只有调用,QuerySet.update方法将不会调用。这个参数只是Date和DateTime以及TimModel.save()方法才会调用e类才有的。
  • DateField.auto_now_add: 第一次添加进去,都会将当前时间设置进去。以后修改,不会修改这个值

本文发布于:2024-02-01 09:07:10,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170674963235538.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

下一篇:FE
标签:
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23