Django models single-table queries

Query from the database is usually the result of a collection, this collection is called QuerySet

  1. View SQL Django QuerySet executed

.query. str () or .query properties of the print execution sql statement

from quicktool.models import User
from django.http import HttpResponse
Creat = User.objects.all().filter(created=1557222940).query.__str__()
return HttpResponse(str(Creat))
#输出结果:SELECT `user`.`表字段1`, `user`.`表所有字段`, FROM `user` WHERE `user`.`created` = 1557222940
复制代码
  1. Django manage.py shell mode offers

Django manage.py into the directory where the execution python manage.py shell into the shell mode

C:\Users\admin>d:
D:\>cd D:\django_test\mytestsite
D:\django_test\mytestsite>python manage.py shell
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
复制代码
  1. values ​​() Returns the dictionary and values_list () Returns the tuple
  • 3.1 Common Object Model

Common mode model object --- with shell print results

>>> from quicktool.models import User
>>> TodayCreat = User.objects.filter(created=1488356162)
>>> print(type(TodayCreat))
<class 'django.db.models.query.QuerySet'>
>>> print(TodayCreat)
<QuerySet [<User: User object (63)>]>
复制代码

Ordinary model objects --- show results with a view URL

from quicktool.models import User
from django.http import HttpResponse
def TodayCreat(request):
    TodayCreat = User.objects.filter(created=1488356162)
    return HttpResponse(TodayCreat)
# 浏览器展示结果:User object (63)
复制代码
  • 3.2 values()

values ​​() Returns a ValuesQuerySet (QuerySet a subclass), the dictionary returns iteration, instead of the model for each instance of an object represents an object dictionary, corresponding to the model name of the key attributes of the object

>>> from quicktool.models import User
>>> TodayCreat = User.objects.filter(created=1488356162).values()
>>> print(type(TodayCreat))
<class 'django.db.models.query.QuerySet'>
>>> print(TodayCreat)
<QuerySet [{'id':63, 'name':'xili','sex':'男'}]>
复制代码

values ​​() Returns the dictionary --- show the results with a view URL

from quicktool.models import User
from django.http import HttpResponse
def TodayCreat(request):
    TodayCreat = User.objects.filter(created=1488356162).values()
    return HttpResponse(TodayCreat)
# 浏览器展示结果:{'id':63, 'name':'xili','sex':'男'}
复制代码

values ​​(* fields), to specify which fields filter, will contain only dictionary return key and the value of the field specified

If the field is not specified, each dictionary comprising key and returns the values ​​for all the fields in the data table

>>> from quicktool.models import User
>>> TodayCreat = User.objects.filter(created=1488356162).values('id','name')
>>> print(type(TodayCreat))
<class 'django.db.models.query.QuerySet'>
>>> print(TodayCreat)
<QuerySet [{'id': 63, 'name': 'xili'}]>
复制代码

values ​​(* fields) returns the dictionary --- show the results with a view URL

from quicktool.models import User
from django.http import HttpResponse
def TodayCreat(request):
    TodayCreat = User.objects.filter(created=1488356162).values('id','name')
    return HttpResponse(TodayCreat)
# 浏览器展示结果:{'id':63, 'name':'xili'}
复制代码
  • 3.3 values_list()

values_list () returns a tuple iteration, rather than dictionary

>>> from quicktool.models import User
>>> TodayCreat = User.objects.filter(created=1488356162).values_list()
>>> print(type(TodayCreat))
<class 'django.db.models.query.QuerySet'>
>>> print(TodayCreat)
<QuerySet [(63, 'xili','男')]>
复制代码

values_list () returns a tuple --- show the results with a view URL

from quicktool.models import User
from django.http import HttpResponse
def TodayCreat(request):
    TodayCreat = User.objects.filter(created=1488356162).values()
    return HttpResponse(TodayCreat)
# 浏览器展示结果:(63,'xili','男')
复制代码

values_list (* fields), to specify which fields filtration, returned tuples comprising only the value of the specified key fields and

If a field is not specified, each tuple key and returned value will contain all the fields in the data table

>>> from quicktool.models import User
>>> TodayCreat = User.objects.filter(created=1488356162).values_list('id','name')
>>> print(type(TodayCreat))
<class 'django.db.models.query.QuerySet'>
>>> print(TodayCreat)
<QuerySet [(63, 'xili')]>
复制代码

values_list (* fields) pass parameters field, not flat pass parameters, return results with tuple --- view showing the URL

from quicktool.models import User
from django.http import HttpResponse
def TodayCreat(request):
    TodayCreat = User.objects.filter(created=1488356162).values('id','name')
    return HttpResponse(TodayCreat)
# 浏览器展示结果:(63,'xili')
复制代码

values_list (* fields), * fields if only one field is transmitted, can be passed flat parameter is True, it represents the result returns a single value, rather than a tuple.

>>> from quicktool.models import User
>>> TodayCreat = User.objects.filter(created=1488356162).values_list('name',flat=True)
>>> print(type(TodayCreat))
<class 'django.db.models.query.QuerySet'>
>>> print(TodayCreat)
<QuerySet ['xili']>
复制代码

values_list (* fields) both pass parameters they pass flat field parameter and returns a tuple --- show the results with a view URL

from quicktool.models import User
from django.http import HttpResponse
def TodayCreat(request):
    TodayCreat = User.objects.filter(created=1488356162).values('name',flat=True)
    return HttpResponse(TodayCreat)
# 浏览器展示结果:xili
复制代码

NOTE: values_list (* fields), * fields passed if more than one field, then the error will be transmitted flat

TypeError: 'flat' is not valid when values_list is called with more than one field.
复制代码

values_list values ​​and return the difference on the result type:

  • vlaues -

A single record - <class 'dict'>

A plurality of records - <class 'django.db.models.query.QuerySet'>

  • vlaues_list -

A single record - <class 'tuple'>

A plurality of records - <class 'django.db.models.query.QuerySet'>

  1. Get Object method
# all():查询所有结果
Person.objects.all() # 查询所有的Person条目
Person.objects.all()[:10] #切片操作,获取10个人,不支持负索引,切片可以节约内存,不支持负索引

# get(**kwargs):返回与所给筛选条件相匹配的对象,返回结果有且只有一个,如果符合筛选条件的对象超过一个或者没有都会抛出错误
Person.objects.get(name="xili") # 名称为 xili 的一条,多条会报错

# filter(**kwargs):返回与所给筛选条件相匹配的对象
Person.objects.filter(name="abc") # 等于Person.objects.filter(name__exact="abc") 名称严格等于 "abc" 的人
Person.objects.filter(name__iexact="abc") # 名称为 abc 但是不区分大小写,可以找到 ABC, Abc, aBC,这些都符合条件
Person.objects.filter(name__contains="abc") # 名称中包含 "abc"的人
Person.objects.filter(name__icontains="abc") #名称中包含 "abc",且abc不区分大小写
Person.objects.filter(name__regex="^abc") # 正则表达式查询
Person.objects.filter(name__iregex="^abc")# 正则表达式不区分大小写
Person.objects .filter(creat__gt=1488356162) # creat时间大于某个时间戳
Person.objects .filter(creat__gte=1488356162) # creat时间大于等于某个时间戳
Person.objects .filter(creat__lt=1488356162) # creat时间小于某个时间戳
Person.objects .filter(creat__lte=1488356162) # creat时间小于等于某个时间戳
Person.objects .filter(creat__range=(start_time, end_time)) # creat时间在start_time和end_time范围内

# exclude(**kwargs):返回与所给筛选条件不匹配的对象
Person.objects.exclude(name__contains="WZ") # 排除包含 WZ 的Person对象
Person.objects.filter(name__contains="abc").exclude(age=23) # 找出名称含有abc, 但是排除年龄是23岁的
复制代码
  1. order_by (): Query results sort in ascending or descending order
# order_by('-id')倒序,order_by('id')升序
# 元组升降序
User.objects.filter(Class_id=5).values_list('id').order_by('-id')
打印结果:(167,)(158,)(144,)(142,)(141,)(140,)(139,)(138,)(137,)(136,)(135,)(118,)(68,)
User.objects.filter(Class_id=5).values_list('id').order_by('id')
打印结果:(68,)(118,)(135,)(136,)(137,)(138,)(139,)(140,)(141,)(142,)(144,)(158,)(167,)
# 字典也能升降序
User.objects.filter(Class_id=5).values('id').order_by('id')
打印结果:{'id': 68}{'id': 118}{'id': 135}{'id': 136}{'id': 137}{'id': 138}{'id': 139}{'id': 140}{'id': 141}{'id': 142}{'id': 144}{'id': 158}{'id': 167}
复制代码
  1. QuerySet does not support negative indexes, ①reverse (): Reverse sort query results ②order_by (): Descending
Person.objects.all()[:10] #切片操作,前10条
Person.objects.all()[-10:] #会报错!提示Negative indexing is not supported.
 
# 1. 使用 reverse() 解决
Person.objects.all().reverse()[:2] # 最后两条
Person.objects.all().reverse()[0] # 最后一条
 
# 2. 使用 order_by() 解决
Author.objects.order_by('-id')[:20] # id最大的20条
复制代码
  1. QuerySet chain support queries
Plan.objects.all().filter(status=3).filter(created__lte=1557331200).filter(finished__gte=1557417599)
User.objects.all().values('created').annotate(count=Count('created')).values('created','count')
Person.objects.filter(name__contains="abc").exclude(age=23)
复制代码
  1. Deduplication

① distinct (): returns the result excluded from duplicate records

qs1 = Pathway.objects.filter(label__name='x')
qs2 = Pathway.objects.filter(reaction__name='A + B >> C')
qs3 = Pathway.objects.filter(inputer__name='xili')

# 合并到一起
qs = qs1 | qs2 | qs3
这个时候就有可能出现重复的
 
# 去重方法
qs = qs.distinct()
复制代码

② set (): python built-in functions, to create an unordered collection of non-repetition

select_UserID = Pathway.objects.filter(inputer__name='xili')
set(select_UserID)
复制代码
  1. list (): to force the changes to the list QuerySet
select_UserID = Pathway.objects.filter(inputer__name='xili')
list(select_UserID)
#结果打印[(532,), (671,), (797,), (532,)]
#原先未转变前打印((532,), (671,), (797,), (532,))
复制代码
  1. total number

① count (): Returns the number of objects in the database match the query (QuerySet) of

User.objects.all().filter(created__range=(today_start_time, today_end_time)).count()
复制代码

② len (): The number of tuples, dictionaries or list element statistics

select_UserID = Pathway.objects.filter(inputer__name='xili')
len(select_UserID)
复制代码
  1. first (): returns the first record; last (): returns the last record
Pathway.objects.filter(inputer__name='xili').first()
Pathway.objects.filter(inputer__name='xili').last()
复制代码
  1. exists (): If QuerySet contains data, returns True, otherwise False
from quicktool.models import User
from django.http import HttpResponse
TodayCreat = User.objects.all().filter(created__range=(today_start_time, today_end_time)).exists()
return HttpResponse(count_TodayCreat)
#能查询出数据则结果为True,不能查询出数据则返回False
复制代码
  1. QuerySet is iterable
es = Entry.objects.all()
for e in es:
    print(e.headline)
复制代码

Reproduced in: https: //juejin.im/post/5cf8c6b151882574ce01387e

Guess you like

Origin blog.csdn.net/weixin_33978044/article/details/91416430