优点:
1.ORM使我们通用的数据库变得更加的简单便捷。
2.可避免新手程序员写sql语句带来的性能问题。
1. 创建单表
2. 创建关键表
1). 一对一
2). 一对多
3). 多对多
创建表的语句:
python manage.py makemigrations
python manage.py migrate
插入:
Author.object.create(**{'name':'wjw'})
修改:
# 方法一 author = models.Author.objects.get(id=5) author.name = 'haha' author.save() # 方法二 models.Author.objects.filter(id=5).update(name='haha')
查询:
.filter(**kwargs) # 集合
.all() # 集合
.get(**kwargs) # 行对象
排序:
au = models.Author.objects.order_by('-id')
.reverse() 对查询结果反向排序
.distinct() 从返回结果中去重
.count() 数量
.first() 取第一条
.last() 取最后一条
.exists() 如果QuerySet中包含数据返回true,否则返回false
一对多:
创建数据表
class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) namebook = models.CharField(max_length=32) nametype = models.CharField(max_length=32)
正向查询
# 正向查询 obj = models.Book.objects.filter(namebook='python')[0] print(obj.author.name) # 连级查询 obj = models.Book.objects.values('namebook', 'author__name')[0] print(obj['namebook'] + "++++" + obj['author__name'])
反向查询
# 反向查询 obj = models.Author.objects.filter(name='lixiangshuai')[0] list = obj.book_set.all().values('namebook') print(list) for item in list: print(item['namebook'])
多对多:
创建多对多数据表
class Teacher(models.Model): name = models.CharField(max_length=32) sex = models.CharField(max_length=32) class Student(models.Model): name = models.CharField(max_length=32) sex = models.CharField(max_length=32) teacher = models.ManyToManyField('Teacher')
正向查询
s = models.Student.objects.filter(name='wangjiawei')[0] t = s.teacher.all() for i in t: print(i.name)
反向查询
t = models.Teacher.objects.get(name='zhangjiong') s = t.student_set.all()
# s = t.student_set.all().values('name')
for i in s:
print(i.name)
基于 __ (双下划綫)的条件查找:
只适用于单表
id__lt = 10, id__gt = 1 # id>1 并且 id<10 id__in = [11, 22, 33] # id = 11,22,33,的数据 .exclude(id__in=[11, 22, 33]) # not in id__range = [1,2] # 范围 bettween··· and ··· name__contains = 'ven' name__icontains = 'ven' # icontains 大小写不敏感 __startwith = 'p' # 开头是 p
聚合查询
.aggregate(*args, **kwargs) # 平均价格 .aggregate(avarage_price = Avg('price')) >>> {'avarage_price':34.35}
Avg 平均值
Min 最小值
Max 最大值
Sum 求和
分组查询
annotate(*args, **kwargs) models.Author.objects.values('author__name').annotate(sum('price'))
完成~! 收工!!~!~!