一、单表操作
1.1 在python的脚本下调用Django环境
import os
if __name__ = = '__main__' :
os.environ.setdefault( "DJANGO_SETTINGS_MODULE" , "day76.settings" )
import django
django.setup()
|
1.2 用orm创建表

from django.db import models
# Create your models here.
class Book(models.Model):
# id 在建表时可以不用写,默认会自动添加
name = models.CharField(max_length=55)
price = models.CharField(max_length=11)
publish = models.CharField(max_length=44)
date = models.DateField(null=True)
# 指定输出显示内容的格式
def __str__(self):
return 'name: %s, price: %s' % (self.name, self.price)
models.py
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py showmigrations
|
1.3 对数据的操作
models.Book.objects.create(name = '阿甘正传' , price = '23' , publish = '环球出版社' , date = '2018-8-8' )
import datetime
c_time = datetime.datetime.now()
book = models.Book(name = '史前人类' , price = '68' , publish = '华夏出版社' , date = c_time)
book.save()
|
models.Book.objects. filter (name = '史前人类' ).delete()
book = models.Book.objects. filter (name = '史前人类' ).first()
book.delete(
|
book = models.Book.objects. filter (name = '阿甘正传' ).update(price = '44' )
book = models.Book.objects. filter (name = '阿甘正传' ).first()
book.price = '55'
book.save()
|
1 > all (): 查询所有结果
2 > filter ( * * kwargs): 它包含了与所给筛选条件相匹配的对象
3 > get( * * kwargs): 返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误。
4 > exclude( * * kwargs): 它包含了与所给筛选条件不匹配的对象
5 > order_by( * field): 对查询结果排序( '-id' )
6 > reverse(): 对查询结果反向排序
7 > count(): 返回数据库中匹配查询(QuerySet)的对象数量。
8 > first(): 返回第一条记录
9 > last(): 返回最后一条记录
10 > exists(): 如果QuerySet包含数据,就返回 True ,否则返回 False
11 > values( * field): 返回一个ValueQuerySet——一个特殊的QuerySet,运行后得到的并不是一系列 model的实例化对象,而是一个可迭代的字典序列
12 > values_list( * field): 它与values()非常相似,它返回的是一个元组序列,values返回的是一个字典序列
13 > distinct(): 从返回结果中剔除重复纪录
|
book = models.Book.objects. all ()
book = models.Book.objects. filter (name = '孝庄秘史' )
book = models.Book.objects.get(name = '阿甘正传' )
book = models.Book.objects.exclude(name = '神秘的西夏王陵' )
book = models.Book.objects. all ().order_by( 'price' )
book = models.Book.objects. all ().order_by( '-price' )
book = models.Book.objects. all ().order_by( 'price' ). filter (name = '阿甘正传' )
book = models.Book.objects. all ().order_by( 'price' ).reverse()
book = models.Book.objects. filter (name = '阿甘正传' ).count()
book = models.Book.objects. filter (name = '阿甘正传' ).last()
book = models.Book.objects. filter (name = '阿甘正传' ).exists()
book = models.Book.objects. all ().values( 'name' )
book = models.Book.objects. all ().values_list( 'name' )
book = models.Book.objects. all ().values( 'name' ).distinct()
|
1.4 数据的模糊查询
Book.objects. filter (price__in = [ 45 , 98 , 56 ]) 价格在[]的书
Book.objects. filter (price__gt = 100 ) 大于
Book.objects. filter (price__lt = 100 ) 小于
Book.objects. filter (price__gte = 100 ) 大于等于
Book.objects. filter (price__lte = 100 ) 小于等于
Book.objects. filter (price__range = [ 100 , 200 ]) 在XX范围内
Book.objects. filter (name__contains = "阿" ) 查询名字有 '%阿%' 的书
Book.objects. filter (name__icontains = "python" ) 查询名字带python的书,忽略大小写
Book.objects. filter (name__startswith = "神" ) 以 '神' 开头的书
Book.objects. filter (date__year = 2017 ) 按年查询
|
二、多表操作
案例:以下面这些概念,字段和关系查询
作者模型:一个作者有姓名和性别及其他详细信息。
作者详细模型:把作者的详情放到详情表,包含手机号,家庭住址等信息。作者详情模型和作者模型之间是一对一的关系(OneToOneField)
出版社模型:出版社有名称,所在城市以及email。
书籍模型: 书籍有书名、价格、作者(一本书可能会有多个作者,一个作者也可以写多本书),所以作者和书籍的关系就是多对多的关联关系(ManyToManyField),但是一本书只应该由一个出版社出版,所以出版社和书籍是一对多的关联关系(ForeignKey)。
|
2.1 创建表操作

from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish = models.ForeignKey(to='Publish', to_field='id')
authors = models.ManyToManyField(to='Author')
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=33)
sex = models.IntegerField()
# 一对一关系建议使用 OneToOneField
author_details = models.OneToOneField(to='AuthorDetails')
def __str__(self):
return self.name
class AuthorDetails(models.Model):
phone = models.CharField(max_length=21)
address = models.CharField(max_length=66)
class Publish(models.Model):
name = models.CharField(max_length=33)
address = models.CharField(max_length=64)
email = models.EmailField()
def __str__(self):
return self.name
'''
注意点:
一对一: OneToOneField
一对多: ForeignKey
多对多: ManyToManyField
OneToOneField 和 ForeignKey 在建模型表时会在字段名后自动添加_id,如:publish_id
ManyToManyField 会自动创建第三张表
'''
models.py
Publish.objects.create(name = '环球出版社' , address = '北京' , email = '0000@foxm.com' )
Publish.objects.create(name = '华夏出版社' , address = '北京' , email = '1111@foxm.com' )
|
publish = Publish.objects. filter (pk = 1 ).first()
Book.objects.create(name = '雷神之诸神之怒' , price = 65.9 , publish = publish)
Book.objects.create(name = '雷神之黑暗世界' , price = 75.3 , publish = publish)
Book.objects.create(name = '雷神之诸神黄昏' , price = 45.5 , publish = publish)
|
AuthorDetails.objects.create(phone = '18800001' , address = '昌平' )
AuthorDetails.objects.create(phone = '16600002' , address = '五环' )
|
au_details = AuthorDetails.objects. filter ( id = 1 ).first()
Author.objects.create(name = 'jack' , sex = 1 , author_details = au_details)
au_details = AuthorDetails.objects. filter ( id = 2 ).first()
Author.objects.create(name = 'peter' , sex = 1 , author_details = au_details)
|
2.2 连表的增删改查
jack = Author.objects. filter (name = 'jack' ).first()
peter = Author.objects. filter (name = 'peter' ).first()
book = Book.objects. filter (name = '雷神之诸神之怒' ).first()
|
book.authors.add(jack, peter)
book.authors.add( 1 , 2 )
book.authors.remove(jack)
book.authors.remove( 1 , 2 )
book.authors.clear()
book.authors. set ([jack,])
|
2.3 基于对象的连表查询
基于对象的连表查询是子查询,即多次查询
正向:由关联字段所在的表去查找其他表时---按字段
反向:由其他表去查找关联字段所在的表时---按表名小写
author = Author.objects. filter (name = 'jack' ).first()
res = author.author_details.phone
print (res)
address = AuthorDetails.objects. filter (address = '五环' ).first()
author = address.author.name
print (author)
|
正向: 由关联字段所在的表去查找其他表时---按字段
反向: 由其他表去查找关联字段所在的表时---按表名小写_set.all()
book = Book.objects. filter (name = '雷神之诸神之怒' ).first()
publish_email = book.publish.email
print (publish_email)
email = Publish.objects. filter (email = '0000@foxm.com' ).first()
book = email.book_set. all (). filter (name = '雷神之诸神黄昏' ).values( 'price' )
print (book)
|
正向: 由关联字段所在的表去查找其他表时---按字段.all()
反向: 由其他表去查找关联字段所在的表时---按表名小写_set.all()
book = Book.objects. filter (name = '雷神之诸神之怒' ).first()
author = book.authors. all ()
print (author)
author = Author.objects. filter (name = 'jack' ).first()
books = author.book_set. all ()
print (books)
|
2.4 基于双下划线的连表查询
***正向查询按字段,反向连表查询按表名小写***
phone = Author.objects. filter (name = 'jack' ).values( 'author_details__phone' )
phone = AuthorDetails.objects. filter (author__name = 'jack' ).values( 'phone' )
print (phone)
|
res = Publish.objects. filter (name = '北京出版社' ).values( 'book__name' , 'book__price' )
res = Book.objects. filter (publish__name = '北京出版社' ).values( 'name' , 'price' )
print (res)
|
authors = Book.objects. filter (name = '雷神之诸神之怒' ).values( 'authors__name' )
authors = Author.objects. filter (book__name = '雷神之诸神之怒' ).values( 'name' )
print (authors)
|
authors = Book.objects. filter (price__gt = 30 ).values( 'authors__name' )
authors = Author.objects. filter (book__price__gt = 30 ).values( 'name' )
print (authors)
|
res = Publish.objects. filter (name = '环球出版社' ).values( 'book__name' , 'book__authors__name' )
print (res)
res1 = Book.objects. filter (publish__name = '环球出版社' ).values( 'name' , 'authors__name' )
print (res1)
res2 = Author.objects. filter (book__publish__name = '环球出版社' ).values( 'book__name' , 'name' )
print (res2)
|
2.5 聚合查询&分组查询
- 聚合查询 .aggregate()
- aggregate()是QuerySet 的一个终止子句,即它返回一个包含一些键值对的字典
from django.db.models import Avg, Min , Max , Sum , Count
avg_price = Book.objects.aggregate(Avg( 'price' ))
max_price = Book.objects.aggregate( Max ( 'price' ))
min_price = Book.objects.aggregate( Min ( 'price' ))
sum_price = Book.objects.aggregate( Sum ( 'price' ))
print (avg_price)
print (max_price)
print (min_price)
print (sum_price)
count = Publish.objects. filter (name = '环球出版社' ).aggregate(Count( 'book' ))
print (count)
|
- 分组查询 .annotate()
- annotate()为调用的 QuerySet中每一个对象都生成一个独立的统计值(统计方法用聚合函数)。
res = Book.objects. all (). filter (name__endswith = '黄昏' ).annotate(num = Count( 'authors' )).values( 'name' , 'num' )
print (res)
res = Book.objects.values( 'name' ). filter (name__endswith = '黄昏' ).annotate(num = Count( 'authors' )).values( 'name' , 'num' )
print (res)
res = Author.objects.values( 'name' ).annotate(num = Sum ( 'book__price' )).values( 'name' , 'num' )
print (res)
|
2.6 F查询 & Q查询
Django 提供 F() 来对两个字段的值做比较。F() 的实例可以在查询中引用字段,来比较同一个 model 实例中两个不同字段的值
from django.db.models import F,Q
res = Book.objects. all ().update(price = F( 'price' ) + 10 )
print (res)
res = Book.objects. filter (Q(authors__name = 'jack' )|Q(authors__name = 'peter' ))
print (res)
|
2.7 常用字段及参数
AutoField - - - - - > int 自增,必须输入参数primary_key = True
CharField(max_length = [ 0 - 255 ]) - - - - - >字符类型,必须提供max_length参数
DateTimeField - - - - - >日期 + 时间格式 YY - MM - DD HH:MM[:ss[.uuuuuu]][TZ]
DateField - - - - - >日期格式 YY - MM - DD
TimeField - - - - - >时间格式 HH:MM[:ss[.uuuuuu]][TZ]
EmailField - - - - - >字符串类型
IntegerField - - - - - >整数( - 2147483648 ~ 2147483647 )
PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField) - - - - - >正整数( 0 ~ 2147483647 )
NullBooleanField - - - - - >可以为空的布尔值
TextField - - - - - >文本类型
|
null - - - - - >表示某个字段可以为空
unique - - - - - >值为 True 时,该字段就必须是唯一的
db_index - - - - - >值为 True 时,为该字段设置索引
default - - - - - >设置默认值
auto_now_add - - - - - >值为 True 时,创建数据记录是会将当前时间添加到数据库
auto_now - - - - - >值为 True 时,每次更新数据记录都会更新该字段
to - - - - - >设置要关联的表
to_field - - - - - >设置要关联的字段
related_name - - - - - >在反向操作时, 使用的字段名,用于代替原反向查询时的 '表名_set'
class Classes(models.Model):
name = models.CharField(max_length = 32 )
class Student(models.Model):
name = models.CharField(max_length = 32 )
theclass = models.ForeignKey(to = "Classes" )
students = models.Classes.objects.first().student_set. all ()
theclass = models.ForeignKey(to = "Classes" , related_name = "students" )
students = models.Classes.objects.first().students. all ()
related_query_name - - - - - >反向查询操作时,使用的连接前缀,用于替换表名
db_constraint - - - - - >是否在数据库中创建外键约束,默认为 True
on_delete - - - - - >当删除关联表中的数据时,当前表与其关联的行的行为
a.与之关联的值设置为指定值,设置:models. SET (值)
b.与之关联的值设置为可执行对象的返回值,设置:models. SET (可执行对象)
db_table - - - - - >默认创建第三张表时,数据库中表的名称
through_fields - - - - - >设置关联的字段
symmetrical - - - - - >仅用于多对多自关联时,指定内部是否创建反向操作的字段。默认为 True
|
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人