欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django model select的多種用法詳解

 更新時(shí)間:2019年07月16日 19:36:51   作者:運(yùn)維咖啡吧  
最近看到 大神 運(yùn)維咖啡吧的 一篇文章,這里只做個(gè)備份,講的是各種 django model 查詢,發(fā)現(xiàn)不錯(cuò),十分感謝該大神的無(wú)私奉獻(xiàn)

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

基本操作

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

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

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

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

常用操作

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

進(jìn)階操作

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

# limit,取第三條以后的數(shù)據(jù),沒(méi)有對(duì)應(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),也沒(méi)有對(duì)應(yīng)SQL,參考上邊的SQL寫法
User.objects.all()[10:20]

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

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

# filter單列、查詢單列,正常values_list給出的結(jié)果是個(gè)列表,里邊里邊的每條數(shù)據(jù)對(duì)應(yīng)一個(gè)元組,當(dāng)只查詢一列時(shí),可以使用flat標(biāo)簽去掉元組,將每條數(shù)據(jù)的結(jié)果以字符串的形式存儲(chǔ)在列表中,從而避免解析元組的麻煩
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'))

時(shí)間字段

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

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

例如下邊的語(yǔ)句

from django.db.models import Q

User.objects.filter(
 Q(role__startswith='sre_'),
 Q(name='公眾號(hào)') | Q(name='運(yùn)維咖啡吧')
)

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

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

通常更多的時(shí)候我們用Q來(lái)做搜索邏輯,比如前臺(tái)搜索框輸入一個(gè)字符,后臺(tái)去數(shù)據(jù)庫(kù)中檢索標(biāo)題或內(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='運(yùn)維咖啡吧')
_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 = '運(yùn)維咖啡吧')
_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ù)庫(kù)里搜索某一條數(shù)據(jù)時(shí),通常使用下邊的方法:

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

但當(dāng)id=724的數(shù)據(jù)不存在時(shí),程序?qū)?huì)拋出一個(gè)錯(cuò)誤

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方法,它會(huì)先調(diào)用django的get方法,如果查詢的對(duì)象不存在的話,則拋出一個(gè)Http404的異常

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

from django.http import Http404

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

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

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

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

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

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

 created = True

returen object, created

執(zhí)行原生SQL

Django中能用ORM的就用它ORM吧,不建議執(zhí)行原生SQL,可能會(huì)有一些安全問(wèn)題,如果實(shí)在是SQL太復(fù)雜ORM實(shí)現(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名的方式

相關(guān)文章

  • Python制作旋轉(zhuǎn)花燈祝大家元宵節(jié)快樂(lè)(實(shí)例代碼)

    Python制作旋轉(zhuǎn)花燈祝大家元宵節(jié)快樂(lè)(實(shí)例代碼)

    一年一度的元宵節(jié)來(lái)臨,小編在這里祝大家2022元宵節(jié)快樂(lè),今天小編給大家分享一篇教程關(guān)于Python制作旋轉(zhuǎn)花燈祝大家元宵節(jié)快樂(lè),代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2022-02-02
  • python讀取mnist數(shù)據(jù)集方法案例詳解

    python讀取mnist數(shù)據(jù)集方法案例詳解

    這篇文章主要介紹了python讀取mnist數(shù)據(jù)集方法案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • python導(dǎo)入不同目錄下的自定義模塊過(guò)程解析

    python導(dǎo)入不同目錄下的自定義模塊過(guò)程解析

    這篇文章主要介紹了python導(dǎo)入不同目錄下的自定義模塊過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Python實(shí)現(xiàn)Linux中的du命令

    Python實(shí)現(xiàn)Linux中的du命令

    這篇文章主要介紹了Python實(shí)現(xiàn)Linux中簡(jiǎn)單du命令,需要的朋友可以參考下
    2017-06-06
  • 三分鐘教會(huì)你用Python+OpenCV批量裁剪xml格式標(biāo)注的圖片

    三分鐘教會(huì)你用Python+OpenCV批量裁剪xml格式標(biāo)注的圖片

    最近學(xué)習(xí)網(wǎng)絡(luò)在線課程的過(guò)程中,為了方便課后復(fù)習(xí),使用手機(jī)截取了大量的圖片,下面這篇文章主要給大家介紹了如何通過(guò)三分鐘教會(huì)你用Python+OpenCV批量裁剪xml格式標(biāo)注圖片的相關(guān)資料,需要的朋友可以參考下
    2022-01-01
  • Django配置文件代碼說(shuō)明

    Django配置文件代碼說(shuō)明

    在本篇文章里小編給大家整理了關(guān)于Django配置文件代碼說(shuō)明知識(shí)點(diǎn),有需要的朋友們學(xué)習(xí)下。
    2019-12-12
  • 關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說(shuō)明

    關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說(shuō)明

    這篇文章主要介紹了關(guān)于tf.matmul() 和tf.multiply() 的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06
  • django model的update時(shí)auto_now不被更新的原因及解決方式

    django model的update時(shí)auto_now不被更新的原因及解決方式

    這篇文章主要介紹了django model的update時(shí)auto_now不被更新的原因及解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-04-04
  • 利用Python抓取阿里云盤資源

    利用Python抓取阿里云盤資源

    相對(duì)于百度云盤,阿里云盤的下載不限速,以及大容量空間深受大家的喜愛。本文將通過(guò)Python實(shí)現(xiàn)抓取阿里云盤的資源,感興趣的可以學(xué)習(xí)一下
    2022-02-02
  • pyCharm 實(shí)現(xiàn)關(guān)閉代碼檢查

    pyCharm 實(shí)現(xiàn)關(guān)閉代碼檢查

    這篇文章主要介紹了pyCharm 實(shí)現(xiàn)關(guān)閉代碼檢查,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06

最新評(píng)論