Django基础010--ORM操作

orm返回的数据有两种,QuerySet,object

1.QuerySet支持链式编程,可以在all()后面继续.方法

teachers = models.Teacher.objects.all()
tea_name = teachers.values('name')#过滤字段,获取我们希望获取的字段
count = teachers.count()#获取qs的个数
firstData = teachers.first()#获取qs的第一个数据
value_name = teachers.values_list('name')#只返回要求过滤的字段的value值不返回key

2.object

teacher = models.Teacher.objects.get(id=1)
teachername = teacher.name

3.orm过滤  filter

teacher = models.Teacher.objects.filter(name__contains='')#过滤 模糊查询
teacher = models.Teacher.objects.filter(name__endswith="")#以什么结尾
teacher = models.Teacher.objects.filter(name__startswith="")#以什么开头
teacher = models.Teacher.objects.filter(name__in=['花开富贵','魏无羡'])#过滤 在什么范围内
teacher = models.Teacher.objects.filter(name__isnull=True)#过滤 为空
teacher = models.Teacher.objects.filter(id__gt=1)#过滤  大于
teacher = models.Teacher.objects.filter(id__gte=1)#过滤  大于等于
teacher = models.Teacher.objects.filter(id__lt=1)#过滤  小于
teacher = models.Teacher.objects.filter(id__lte=1)#过滤  小于等于
student = models.Student.objects.filter(id__range=[1,4])#过滤  小于

4.排除

#排除
#除了name=花开富贵的,其他的都查询出来
teacher = models.Teacher.objects.exclude(name='花开富贵')

5.多条件查询

#and  where id = 1 and name = '魏无羡'
teacher = models.Teacher.objects.filter(id=1,name='魏无羡')


#or操作
#导入from django.db.models import Q
#where id = 1 or name = 魏无羡
teacher = models.Teacher.objects.filter(Q(id=1) | Q(name='魏无羡'))#or 只要条件满足 就把数据都查询出来


#where id = 1 and name = '魏无羡'
teacher = models.Teacher.objects.filter(Q(id=1) & Q(name='魏无羡'))#and 条件同时满足,查询数据



#where id = 1 and name != '魏无羡'
teacher = models.Teacher.objects.filter(Q(id=1) & ~Q(name='魏无羡'))#and 取反

 

posted @ 2020-09-03 21:30  cjxxl1213  阅读(171)  评论(0编辑  收藏  举报