溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django model select的多種用法詳解

發(fā)布時間:2020-10-13 00:13:06 來源:腳本之家 閱讀:145 作者:運維咖啡吧 欄目:開發(fā)技術(shù)

《Django model update的各種用法介紹》文章介紹了Django model的各種update操作,這篇文章就是她的姊妹篇,詳細介紹Django model select的用法,配以對應(yīng)MySQL的查詢語句,理解起來更輕松。

基本操作

# 獲取所有數(shù)據(jù),對應(yīng)SQL:select * from User
User.objects.all()

# 匹配,對應(yīng)SQL:select * from User where name = '運維咖啡吧'
User.objects.filter(name='運維咖啡吧')

# 不匹配,對應(yīng)SQL:select * from User where name != '運維咖啡吧'
User.objects.exclude(name='運維咖啡吧')

# 獲取單條數(shù)據(jù)(有且僅有一條,id唯一),對應(yīng)SQL:select * from User where id = 724
User.objects.get(id=123)

常用操作

# 獲取總數(shù),對應(yīng)SQL:select count(1) from User
User.objects.count()

# 獲取總數(shù),對應(yīng)SQL:select count(1) from User where name = '運維咖啡吧'
User.objects.filter(name='運維咖啡吧').count()

# 大于,>,對應(yīng)SQL:select * from User where id > 724
User.objects.filter(id__gt=724)

# 大于等于,>=,對應(yīng)SQL:select * from User where id >= 724
User.objects.filter(id__gte=724)

# 小于,<,對應(yīng)SQL:select * from User where id < 724
User.objects.filter(id__lt=724)

# 小于等于,<=,對應(yīng)SQL:select * from User where id <= 724
User.objects.filter(id__lte=724)

# 同時大于和小于, 1 < id < 10,對應(yīng)SQL:select * from User where id > 1 and id < 10
User.objects.filter(id__gt=1, id__lt=10)

# 包含,in,對應(yīng)SQL:select * from User where id in (11,22,33)
User.objects.filter(id__in=[11, 22, 33])

# 不包含,not in,對應(yīng)SQL:select * from User where id not in (11,22,33)
User.objects.exclude(id__in=[11, 22, 33])

# 為空:isnull=True,對應(yīng)SQL:select * from User where pub_date is null
User.objects.filter(pub_date__isnull=True)

# 不為空:isnull=False,對應(yīng)SQL:select * from User where pub_date is not null
User.objects.filter(pub_date__isnull=True)

# 匹配,like,大小寫敏感,對應(yīng)SQL:select * from User where name like '%sre%',SQL中大小寫不敏感
User.objects.filter(name__contains="sre")

# 匹配,like,大小寫不敏感,對應(yīng)SQL:select * from User where name like '%sre%',SQL中大小寫不敏感
User.objects.filter(name__icontains="sre")

# 不匹配,大小寫敏感,對應(yīng)SQL:select * from User where name not like '%sre%',SQL中大小寫不敏感
User.objects.exclude(name__contains="sre")

# 不匹配,大小寫不敏感,對應(yīng)SQL:select * from User where name not like '%sre%',SQL中大小寫不敏感
User.objects.exclude(name__icontains="sre")

# 范圍,between and,對應(yīng)SQL:select * from User where id between 3 and 8
User.objects.filter(id__range=[3, 8])

# 以什么開頭,大小寫敏感,對應(yīng)SQL:select * from User where name like 'sh%',SQL中大小寫不敏感
User.objects.filter(name__startswith='sre')

# 以什么開頭,大小寫不敏感,對應(yīng)SQL:select * from User where name like 'sh%',SQL中大小寫不敏感
User.objects.filter(name__istartswith='sre')

# 以什么結(jié)尾,大小寫敏感,對應(yīng)SQL:select * from User where name like '%sre',SQL中大小寫不敏感
User.objects.filter(name__endswith='sre')

# 以什么結(jié)尾,大小寫不敏感,對應(yīng)SQL:select * from User where name like '%sre',SQL中大小寫不敏感
User.objects.filter(name__iendswith='sre')

# 排序,order by,正序,對應(yīng)SQL:select * from User where name = '運維咖啡吧' order by id
User.objects.filter(name='運維咖啡吧').order_by('id')

# 多級排序,order by,先按name進行正序排列,如果name一致則再按照id倒敘排列
User.objects.filter(name='運維咖啡吧').order_by('name','-id')

# 排序,order by,倒序,對應(yīng)SQL:select * from User where name = '運維咖啡吧' order by id desc
User.objects.filter(name='運維咖啡吧').order_by('-id')

進階操作

# limit,對應(yīng)SQL:select * from User limit 3;
User.objects.all()[:3]

# limit,取第三條以后的數(shù)據(jù),沒有對應(yīng)的SQL,類似的如:select * from User limit 3,10000000,從第3條開始取數(shù)據(jù),取10000000條(10000000大于表中數(shù)據(jù)條數(shù))
User.objects.all()[3:]

# offset,取出結(jié)果的第10-20條數(shù)據(jù)(不包含10,包含20),也沒有對應(yīng)SQL,參考上邊的SQL寫法
User.objects.all()[10:20]

# 分組,group by,對應(yīng)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,對應(yīng)SQL:select distinct(username) from User
User.objects.values('username').distinct().count()

# filter多列、查詢多列,對應(yīng)SQL:select username,fullname from accounts_user
User.objects.values_list('username', 'fullname')

# filter單列、查詢單列,正常values_list給出的結(jié)果是個列表,里邊里邊的每條數(shù)據(jù)對應(yīng)一個元組,當只查詢一列時,可以使用flat標簽去掉元組,將每條數(shù)據(jù)的結(jié)果以字符串的形式存儲在列表中,從而避免解析元組的麻煩
User.objects.values_list('username', flat=True)

# int字段取最大值、最小值、綜合、平均數(shù)
from django.db.models import Sum,Count,Max,Min,Avg

User.objects.aggregate(Count(‘id'))
User.objects.aggregate(Sum(‘a(chǎn)ge'))

時間字段

# 匹配日期,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)


# 按天統(tǒng)計歸檔
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對象可以對關(guān)鍵字參數(shù)進行封裝,從而更好的應(yīng)用多個查詢,可以組合&(and)、|(or)、~(not)操作符。

例如下邊的語句

from django.db.models import Q

User.objects.filter(
 Q(role__startswith='sre_'),
 Q(name='公眾號') | Q(name='運維咖啡吧')
)

轉(zhuǎn)換成SQL語句如下:

select * from User where role like 'sre_%' and (name='公眾號' or name='運維咖啡吧')

通常更多的時候我們用Q來做搜索邏輯,比如前臺搜索框輸入一個字符,后臺去數(shù)據(jù)庫中檢索標題或內(nèi)容中是否包含

_s = request.GET.get('search')

_t = Blog.objects.all()
if _s:
 _t = _t.filter(
 Q(title__icontains=_s) |
 Q(content__icontains=_s)
 )

return _t

外鍵:ForeignKey

表結(jié)構(gòu):

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='運維咖啡吧')
_t.role.name

反向查詢:

# 查詢角色下包含的所有用戶
_t = Role.objects.get(name='Role03')
_t.user_set.all()

另一種反向查詢的方法:

_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

表結(jié)構(gòu):

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 = '運維咖啡吧')
_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

正常如果我們要去數(shù)據(jù)庫里搜索某一條數(shù)據(jù)時,通常使用下邊的方法:

_t = User.objects.get(id=734)

但當id=724的數(shù)據(jù)不存在時,程序?qū)伋鲆粋€錯誤

abcer.models.DoesNotExist: User matching query does not exist.

為了程序兼容和異常判斷,我們可以使用下邊兩種方式:

方式一:get改為filter

_t = User.objects.filter(id=724)
# 取出_t之后再去判斷_t是否存在

方式二:使用get_object_or_404

from django.shortcuts import get_object_or_404

_t = get_object_or_404(User, id=724)
# get_object_or_404方法,它會先調(diào)用django的get方法,如果查詢的對象不存在的話,則拋出一個Http404的異常

實現(xiàn)方法類似于下邊這樣:

from django.http import Http404

try:
 _t = User.objects.get(id=724)
except User.DoesNotExist:
 raise Http404
get_or_create

顧名思義,查找一個對象如果不存在則創(chuàng)建,如下:

object, created = User.objects.get_or_create(username='運維咖啡吧')

返回一個由object和created組成的元組,其中object就是一個查詢到的或者是被創(chuàng)建的對象,created是一個表示是否創(chuàng)建了新對象的布爾值

實現(xiàn)方式類似于下邊這樣:

try:
 object = User.objects.get(username='運維咖啡吧')
 created = False
exception User.DoesNoExist:
 object = User(username='運維咖啡吧')
 object.save()

 created = True

returen object, created

執(zhí)行原生SQL

Django中能用ORM的就用它ORM吧,不建議執(zhí)行原生SQL,可能會有一些安全問題,如果實在是SQL太復雜ORM實現(xiàn)不了,那就看看下邊執(zhí)行原生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名的方式

Django model select的多種用法詳解

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI