Django model select的各類用法詳解

《Django model update的各類用法介紹》文章介紹了Django model的各類update操做,這篇文章就是她的姊妹篇,詳細介紹Django model select的用法,配以對應MySQL的查詢語句,理解起來更輕鬆。mysql

基本操做

# 獲取全部數據,對應SQL:select * from User
User.objects.all()

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

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

# 獲取單條數據(有且僅有一條,id惟一),對應SQL:select * from User where id = 724
User.objects.get(id=123)
複製代碼

經常使用操做

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

# 比較,gt:>,gte:>=,lt:<,lte:<=,對應SQL:select * from User where id > 724
User.objects.filter(id__gt=724)
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])
User.objects.exclude(id__in=[11, 22, 33])

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

# like,contains大小寫敏感,icontains大小寫不敏感,相同用法的還有startswith、endswith
User.objects.filter(name__contains="sre")
User.objects.exclude(name__contains="sre")

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

# 排序,order by,'id'按id正序,'-id'按id倒敘
User.objects.filter(name='運維咖啡吧').order_by('id')
User.objects.filter(name='運維咖啡吧').order_by('-id')

# 多級排序,order by,先按name進行正序排列,若是name一致則再按照id倒敘排列
User.objects.filter(name='運維咖啡吧').order_by('name','-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’))
複製代碼

時間字段

# 匹配日期,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,相同用法的還有匹配月month,匹配日day,匹配周week_day,匹配時hour,匹配分minute,匹配秒second
User.objects.filter(create_time__year=2018)
User.objects.filter(create_time__year__gte=2018)

# 按天統計歸檔
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)操做符。sql

例以下邊的語句數據庫

from django.db.models import Q

User.objects.filter(
    Q(role__startswith='sre_'),
    Q(name='公衆號') | Q(name='運維咖啡吧')
)
複製代碼

轉換成SQL語句以下:django

select * from User where role like 'sre_%' and (name='公衆號' or name='運維咖啡吧')
複製代碼

一般更多的時候咱們用Q來作搜索邏輯,好比前臺搜索框輸入一個字符,後臺去數據庫中檢索標題或內容中是否包含安全

_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

  • 表結構:
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以下:bash

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屬性取到某角色的全部用戶app

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

正常若是咱們要去數據庫裏搜索某一條數據時,一般使用下邊的方法:fetch

_t = User.objects.get(id=734)
複製代碼

但當id=724的數據不存在時,程序將會拋出一個錯誤ui

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方法,它會先調用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='運維咖啡吧')

複製代碼

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

實現方式相似於下邊這樣:

try:
    object = User.objects.get(username='運維咖啡吧')
    
    created = False
exception User.DoesNoExist:
    object = User(username='運維咖啡吧')
    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名的方式

掃碼關注公衆號查看更多原創文章
相關文章
相關標籤/搜索