查询数据
创建模型
from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
def __str__(self):
return self.name
class Entry(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateField()
mod_date = models.DateField()
authors = models.ManyToManyField(Author)
number_of_comments = models.IntegerField()
number_of_pingbacks = models.IntegerField()
rating = models.IntegerField()
def __str__(self):
return self.headline
使用单独的脚本测试模型
tests/test.py
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
# 测试模型
all = Blog.objects.all().values()
print(all)
创建对象
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
b.save()
通过create创建
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
b = Blog.objects.create(name='测试', tagline='abc')
使用管理器重写create方法
创建管理器:
class BlogManager(models.Manager): # 继承默认的管理器
def create(self, name, tagline):
blog = super().create(name=name, tagline=tagline)
# 将你的个人代码放在这里
print('测试一下是否工作正常')
return blog
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
objects = BlogManager()
def __str__(self):
return self.name
调用create方法创建:
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
b = Blog.objects.create(name='测试2', tagline='abc2')
通过save修改
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
b = Blog.objects.get(id=1)
b.name = "这个是id为1的blog"
b.save()
重写save方法
注意,save方法要重写,是在模型类本身上实现而不是管理器中实现的。如果我们需要在修改的前后执行某些逻辑,我们通常都需要重新实现save方法。
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
objects = BlogManager()
def __str__(self):
return self.name
def save(self, *args, **kwargs):
print("执行更新之前。。。")
super().save(*args, **kwargs) # 一定不要忘记这行代码
print("执行更新之后。。。")
调用save方法修改:
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
b = Blog.objects.get(id=1)
b.name = "这个是id为1的blog 2222"
b.save()
查询所有数据
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Blog
if __name__ == "__main__":
print(Blog.objects.all())
查询符合条件的所有数据
准备模型
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=72)
age = models.IntegerField()
birthday = models.DateTimeField()
salary = models.DecimalField(max_digits=13, decimal_places=2)
def __str__(self):
return self.name
exact精确匹配
示例:查询名字叫Zhangsan的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__exact='Zhangsan')
print(employees)
# 清空
employees.delete()
iexact不区分大小写的精确匹配
示例:查询名字叫zhangsan的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__iexact='zhangsan')
print(employees)
# 清空
employees.delete()
contains包含匹配
示例:查询名字中包含sa的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__contains='sa')
print(employees)
# 清空
employees.delete()
icontains不区分大小写的包含匹配
示例:查询名字中包含SA的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__icontains='SA')
print(employees)
# 清空
employees.delete()
in在..之内的匹配
示例:查询名字在[‘Zhangsan’,’Lisi’]中的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__in=['Zhangsan', 'Lisi'])
print(employees)
# 清空
employees.delete()
gt大于
示例:查询年龄大于20岁的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(age__gt=20)
print(employees)
# 清空
employees.delete()
gte大于等于
示例:查询年龄大于或等于22岁的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(age__gte=22)
print(employees)
# 清空
employees.delete()
lt小于
示例:查询年龄小于30岁的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(age__lt=30)
print(employees)
# 清空
employees.delete()
lte小于等于
示例:查询年龄小于或等于22岁的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(age__lte=22)
print(employees)
# 清空
employees.delete()
startswith从开头匹配
示例:查询名字以Zh开头的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__startswith='Zh')
print(employees)
# 清空
employees.delete()
istartswith不区分大小写从开头匹配
示例:查询名字以zhang开头的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__istartswith='zhang')
print(employees)
# 清空
employees.delete()
endswith从结尾处匹配
示例:查询名字以san结尾的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__endswith='san')
print(employees)
# 清空
employees.delete()
iendswith不区分大小写从结尾处匹配
示例:查询名字以SAN结尾的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(name__iendswith='SAN')
print(employees)
# 清空
employees.delete()
range范围匹配
示例:查询年龄在20-30岁之间的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(age__range=(20, 30))
print(employees)
# 清空
employees.delete()
示例2:查询生日在1993年-2022年出生的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 生日1993-2022年
start = datetime.datetime(1993, 1, 1, 0, 0, 0, tzinfo=tz)
end = datetime.datetime(2022, 1, 1, 0, 0, 0, tzinfo=tz)
# 查询员工
employees = Employee.objects.filter(birthday__range=[start, end])
print(employees)
# 清空
employees.delete()
上面问题的其他方案:
Employee.objects.filter(birthday__gt=start).filter(birthday__lt=end)
Employee.objects.filter(birthday__gt=start, birthday__lt=end)
这里这个案例主要需要学习到以下知识点:
除了数字类型支持range意外,日期类型也是支持range的
filter支持多个调用链,多个filter之间是且的关系,查询结果要同时满足所有filter给出的条件
filter的参数可以有多个,默认多个参数之间是且关系,查询结果必须要同时满足filter中给出的所有条件
year年份
示例:查询2021年出生的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(birthday__year=2021)
print(employees)
# 清空
employees.delete()
month月份
示例:查询12月份出生的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(birthday__month=12)
print(employees)
# 清空
employees.delete()
day日期
示例:查询12号出生的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.filter(birthday__day=12)
print(employees)
# 清空
employees.delete()
查询不符合条件的所有数据
exclude(**kwargs):返回除了根据指定参数查询出来结果的QuerySet。
示例:查询名字里不包含Lisi的员工
import os
import sys
# 设置目录查找路径
sys.path.insert(0, '../../')
# 设置Django配置信息
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hello_django.settings')
import django
django.setup()
# 导入模型
from index.models import Employee
import datetime
from django.utils import timezone
if __name__ == "__main__":
# 添加员工
tz = timezone.get_current_timezone()
zs = {
"name": "Zhangsan",
"age": 22,
"birthday": datetime.datetime(2021, 12, 12, 0, 0, 0, tzinfo=tz),
"salary": 33333,
}
Employee.objects.create(**zs)
# 查询员工
employees = Employee.objects.exclude(name__contains='Lisi')
print(employees)
# 清空
employees.delete()
F表达式
查询 JSONField
Q对象
领取专属 10元无门槛券
私享最新 技术干货