ORM基础3 在python脚本里调用Django环境
1、查询
1.# all获取所有的object,结果QuerySet,列表 print('all'.center(80, '=')) ret = models.Person.objects.all() print(ret) 2.# filter 删选;结果:QuerySet list;不会报错,结果为空 print('filter'.center(80, '=')) ret = models.Person.objects.filter(id=1) print(ret) 3.# 对象 若对象不存在,则报错 print("get".center(80, '=')) ret = models.Person.objects.get(id=1) print(ret) 4.# exclude除了 结果:QuerySet list print("exclude".center(80, "=")) ret = models.Person.objects.exclude(id=1) print(ret) 5.# values 查询字段 结果:QuerySet list dict print("values".center(80, "=")) ret = models.Person.objects.values("name", "age") print(ret) 6.# values_list 字段 结果:QuerySet list tuple print("values_list".center(80, "=")) ret = models.Person.objects.values_list("name", "age") print(ret) 7.# order_by 排序(正序) 结果:QuerySet list print("order_by".center(80, "=")) ret = models.Person.objects.order_by("age") print(ret) 8.# reverse 取反,结果:QuerySet list 注意:reverse()前必须先排序 print("reverse".center(80, "=")) ret = models.Person.objects.order_by("age").reverse() print(ret) 9.# count 计数有几行数据(包含表头) print("count".center(80, "=")) ret = models.Book.objects.count() print(ret) 10.# 查看第一个元素 print("first".center(80, "=")) ret = models.Book.objects.first() print(ret) 11.# 查看最后一个元素 print("last".center(80, "=")) ret = models.Person.objects.last() print(ret) 12.# 查看是否存在数据行 print("exists".center(80, "=")) ret = models.Person.objects.exists() print(ret)
QuerySet
1. all() 2. filter() 3. exclude() 4.values() 字典 5.values_list() 元祖 6.order_by() 7.reverse()
对象
1.get() 2.first() 3.laste()
其它
count()
2、神奇的双下方法-->根据字段查询
1.# lt(小于) gt(大于) lte(小于等于) gte(大于等于) ret = models.Person.objects.filter(id__gt=2, id__lte=4) print(ret) ret = models.Person.objects.filter(id__gte=2, id__lt=4) print(ret) 2.# in not in print("in and not in".center(80, "*")) ret = models.Person.objects.filter(id__in=[1, 3, 4]) print(ret) ret = models.Person.objects.exclude(id__in=[1, 3]) print(ret) 3.# range 相对于 mysql的between and 是闭区间 print("range".center(80, "*")) ret = models.Person.objects.filter(id__range=[2, 4]) print(ret) 4.# contains 相当于mysql like '%o%',icontains不区分大小写 print("contains".center(80, "*")) ret = models.Person.objects.filter(name__contains="o") print(ret) ret = models.Person.objects.filter(name__icontains="o") print(ret) 5.# startswith 以什么开始 ,含有i不区分大小写 ret = models.Person.objects.filter(name__startswith='t') print(ret) ret = models.Person.objects.filter(name__istartswith='t') print(ret) 6.# endswith 以什么结尾,带i的不区分大小写 ret = models.Person.objects.filter(name__endswith='r') print(ret) 7.# 日期 year month day ret = models.Person.objects.filter(birthday__day=15) print(ret)
注意:字段__判断条件
3、在python脚本里调用Django环境
import os if __name__ == "__main__": # manage.py 文件里有 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite04.settings') import django django.setup() from app01 import models