Django model select獲取數據詳細講解html
基本操做mysql
# 獲取全部數據,對應SQL:select * from User User.objects.all() # 匹配,對應SQL:select * from User where name = 'Pala' User.objects.filter(name='Pala') # 不匹配,對應SQL:select * from User where name != 'Pala' User.objects.exclude(name='Pala') # 獲取單條數據(有且僅有一條,id惟一),對應SQL:select * from User where id = 724 User.objects.get(id=123)
經常使用操做sql
# 獲取總數,對應SQL:select count(1) from User User.objects.count() # 獲取總數,對應SQL:select count(1) from User where name = 'Pala' User.objects.filter(name='Pala').count() # 大於,>,對應SQL:select * from User where id > 724 User.objects.filter(id__gt=724) # 大於等於,>=,對應SQL:select * from User where id >= 724 User.objects.filter(id__gte=724) # 小於,<,對應SQL:select * from User where id < 724 User.objects.filter(id__lt=724) # 小於等於,<=,對應SQL:select * from User where id <= 724 User.objects.filter(id__lte=724) # 同時大於和小於, 1 < id < 10,對應SQL:select * from User where id > 1 and id < 10 User.objects.filter(id__gt=1, id__lt=10) # 包含,in,對應SQL:select * from User where id in (11,22,33) User.objects.filter(id__in=[11, 22, 33]) # 不包含,not in,對應SQL:select * from User where id not in (11,22,33) User.objects.exclude(id__in=[11, 22, 33]) # 爲空:isnull=True,對應SQL:select * from User where pub_date is null User.objects.filter(pub_date__isnull=True) # 不爲空:isnull=False,對應SQL:select * from User where pub_date is not null User.objects.filter(pub_date__isnull=True) # 匹配,like,大小寫敏感,對應SQL:select * from User where name like '%sre%',SQL中大小寫不敏感 User.objects.filter(name__contains="sre") # 匹配,like,大小寫不敏感,對應SQL:select * from User where name like '%sre%',SQL中大小寫不敏感 User.objects.filter(name__icontains="sre") # 不匹配,大小寫敏感,對應SQL:select * from User where name not like '%sre%',SQL中大小寫不敏感 User.objects.exclude(name__contains="sre") # 不匹配,大小寫不敏感,對應SQL:select * from User where name not like '%sre%',SQL中大小寫不敏感 User.objects.exclude(name__icontains="sre") # 範圍,between and,對應SQL:select * from User where id between 3 and 8 User.objects.filter(id__range=[3, 8]) # 以什麼開頭,大小寫敏感,對應SQL:select * from User where name like 'sh%',SQL中大小寫不敏感 User.objects.filter(name__startswith='sre') # 以什麼開頭,大小寫不敏感,對應SQL:select * from User where name like 'sh%',SQL中大小寫不敏感 User.objects.filter(name__istartswith='sre') # 以什麼結尾,大小寫敏感,對應SQL:select * from User where name like '%sre',SQL中大小寫不敏感 User.objects.filter(name__endswith='sre') # 以什麼結尾,大小寫不敏感,對應SQL:select * from User where name like '%sre',SQL中大小寫不敏感 User.objects.filter(name__iendswith='sre') # 排序,order by,正序,對應SQL:select * from User where name = 'Pala' order by id User.objects.filter(name='Pala').order_by('id') # 多級排序,order by,先按name進行正序排列,若是name一致則再按照id倒敘排列 User.objects.filter(name='Pala').order_by('name','-id') # 排序,order by,倒序,對應SQL:select * from User where name = 'Pala' order by id desc User.objects.filter(name='Pala').order_by('-id')
進階操做數據庫
# limit,對應SQL:select * from User limit 3; User.objects.all()[:3] # limit,取第三條之後的數據,沒有對應的SQL, # 相似的如:select * from User limit 3,10000000,從第3條開始取數據,取10000000條(10000000大於表中數據條數) User.objects.all()[3:] # offset,取出結果的第10-20條數據(不包含10,包含20),也沒有對應SQL,參考上邊的SQL寫法 User.objects.all()[10:20] # 分組,group by,對應SQL:select username,count(1) from User group by username; from django.db.models import Count User.objects.values_list('username').annotate(Count('id')) # 去重distinct,對應SQL:select distinct(username) from User User.objects.values('username').distinct().count() # filter多列、查詢多列,對應SQL:select username,fullname from accounts_user User.objects.values_list('username', 'fullname') # filter單列、查詢單列,正常values_list給出的結果是個列表, # 裏邊裏邊的每條數據對應一個元組,當只查詢一列時,能夠使用flat標籤去掉元組, # 將每條數據的結果以字符串的形式存儲在列表中,從而避免解析元組的麻煩 User.objects.values_list('username', flat=True) # int字段取最大值、最小值、綜合、平均數 from django.db.models import Sum,Count,Max,Min,Avg User.objects.aggregate(Count(‘id’)) User.objects.aggregate(Sum(‘age’))
時間查詢django
# 匹配日期,date User.objects.filter(create_time__date=datetime.date(2018, 8, 1)) User.objects.filter(create_time__date__gt=datetime.date(2018, 8, 2)) # 匹配年,year User.objects.filter(create_time__year=2018) User.objects.filter(create_time__year__gte=2018) # 匹配月,month User.objects.filter(create_time__month__gt=7) User.objects.filter(create_time__month__gte=7) # 匹配日,day User.objects.filter(create_time__day=8) User.objects.filter(create_time__day__gte=8) # 匹配周,week_day User.objects.filter(create_time__week_day=2) User.objects.filter(create_time__week_day__gte=2) # 匹配時,hour User.objects.filter(create_time__hour=9) User.objects.filter(create_time__hour__gte=9) # 匹配分,minute User.objects.filter(create_time__minute=15) User.objects.filter(create_time__minute_gt=15) # 匹配秒,second User.objects.filter(create_time__second=15) User.objects.filter(create_time__second__gte=15) # 按天統計歸檔 today = datetime.date.today() select = {'day': connection.ops.date_trunc_sql('day', 'create_time')} deploy_date_count = Task.objects.filter( create_time__range=(today - datetime.timedelta(days=7), today) ).extra(select=select).values('day').annotate(number=Count('id'))
Q的使用安全
Q對象能夠對關鍵字參數進行封裝,從而更好的應用多個查詢,能夠組合&(and)、|(or)、~(not)操做符。app
例以下邊的語句post
from django.db.models import Q User.objects.filter( Q(role__startswith='sre_'), Q(name='公衆號') | Q(name='Pala') )
轉換成SQL語句以下:fetch
select * from User where role like 'sre_%' and (name='Tom' or name='Pala')
一般更多的時候咱們用Q來作搜索邏輯,好比前臺搜索框輸入一個字符,後臺去數據庫中檢索標題或內容中是否包含spa
_s = request.GET.get('search') _t = Blog.objects.all() if _s: _t = _t.filter( Q(title__icontains=_s) | Q(content__icontains=_s) )
外鍵:ForeignKey
表的結構:
class Role(models.Model): name = models.CharField(max_length=16, unique=True) class User(models.Model): username = models.EmailField(max_length=255, unique=True) role = models.ForeignKey(Role, on_delete=models.CASCADE)
正向查詢:
# 查詢用戶的角色名 _t = User.objects.get(username='Pala') _t.role.name
反向查詢
# 查詢用戶的角色名 _t = User.objects.get(username='pala') _t.role.name
第二種反向查詢:
_t = Role.objects.get(name='Role03') # 這種方法比上一種_set的方法查詢速度要快 User.objects.filter(role=_t)
第三種反向查詢:
若是外鍵字段有related_name屬性,例如models以下:
class User(models.Model): username = models.EmailField(max_length=255, unique=True) role = models.ForeignKey(Role, on_delete=models.CASCADE,related_name='roleUsers')
那麼能夠直接用related_name屬性取到某角色的全部用戶
_t = Role.objects.get(name = 'Role03') _t.roleUsers.all()
M2M:ManyToManyField
表結構:
class Group(models.Model): name = models.CharField(max_length=16, unique=True) class User(models.Model): username = models.CharField(max_length=255, unique=True) groups = models.ManyToManyField(Group, related_name='groupUsers')
正向查詢:
# 查詢用戶隸屬組 _t = User.objects.get(username = 'Pala') _t.groups.all()
反向查詢:
# 查詢組包含用戶 _t = Group.objects.get(name = 'groupC') _t.user_set.all()
一樣M2M字段若是有related_name屬性,那麼能夠直接用下邊的方式反查
_t = Group.objects.get(name = 'groupC') _t.groupUsers.all()
get_object_or_404
正常若是咱們要去數據庫裏搜索某一條數據時,一般使用下邊的方法:
_t = User.objects.get(id=734)
但當id=724的數據不存在時,程序將會拋出一個錯誤
abcer.models.DoesNotExist: User matching query does not exist.
爲了程序兼容和異常判斷,咱們能夠使用下邊兩種方式:
方式一:get改成filter
_t = User.objects.filter(id=724)
方式二:使用get_object_or_404
from django.shortcuts import get_object_or_404 _t = get_object_or_404(User, id=724)
# get_object_or_404方法,它會先調用django的get方法,若是查詢的對象不存在的話,則拋出一個Http404的異常
實現方法相似於下邊這樣:
from django.http import Http404 try: _t = User.objects.get(id=724) except User.DoesNotExist: raise Http404
get_or_create
顧名思義,查找一個對象若是不存在則建立,以下
object, created = User.objects.get_or_create(username='Pala')
原文:http://www.chenxm.cc/post/657.html
返回一個由object和created組成的元組,其中object就是一個查詢到的或者是被建立的對象,created是一個表示是否建立了新對象的布爾值
實現方式相似於下邊這樣:
try:
object = User.objects.get(username='Pala') created = False exception User.DoesNoExist: object = User(username='Pala') object.save() created = True returen object, created
執行原生SQL
Django中能用ORM的就用它ORM吧,不建議執行原生SQL,可能會有一些安全問題,若是實在是SQL太複雜ORM實現不了,那就看看下邊執行原生SQL的方法,跟直接使用pymysql基本一致了
from django.db import connection with connection.cursor() as cursor: cursor.execute('select * from accounts_User') row = cursor.fetchall() return row
注意這裏表名字要用app名+下劃線+model名的方式
相關文章:
https://www.cnblogs.com/chenxinming-top/p/9473098.html
https://www.cnblogs.com/chenxinming-top/p/9473086.html
https://www.cnblogs.com/chenxinming-top/p/9448558.html