1. 程式人生 > 實用技巧 >Django-ORM的基本操作

Django-ORM的基本操作

Django-ORM的基本操作

表結構如下:
from django.db import models
class Book(models.Model):
	BookId = models.AutoField(primary_key = True)	#定義主鍵id
    bookName = models.CharField(max_length = 50, verbose_name = "書名")
    authorId = models.ForeignKey("app.Author", on_delete=models.DO_NOTHING)#外來鍵關聯
    publicTime = models.DateTimeField(auto_now_add = True)

class Author(models.Model):
    authorId = models.AutoField(primary_key = True)
    authorName = models.CharField(max_length = 50, verbose_name = "作者名字")
    age = models.IntegerField(blank=True, null=True)
    sex = models.CharField(max_length = 10, verbose_name = "性別")

models的定義是為了把資料庫表對映為python的 物件。

類名對應資料表的名字, 類的欄位對應資料表的欄位。

一個類的例項 對映資料表中的一條資料。

queryset物件是django的定義,包含 多個例項物件的可迭代物件

一、單條資料物件的基本操作

#增加資料,兩種方法,都返回資料物件,第二種需要執行save()提交資料。
author_obj = Author.objects.create(authorId = 1, authorName = "小明", age = 18)

author_obj = Author(authorId = 1, authorName = "小明", age = 18)
author_obj.save()

#刪除資料
author_obj.delete()

#修改資料,直接賦值,最後執行 author_obj.save() 提交修改
author_obj.authorName = "小紅"
author_obj.authorId = 2
author_obj.save()

#查詢資料,該方法只能查詢唯一的資料,如果查詢的欄位重複,會報錯。
author_obj = Author.objects.get(authorId = 1)

#沒有查詢到資料,會建立一個。
author_obj = Author.objects.get_or_create(authorId = 1)
print(author_obj)
<Author: Author object (1)>

二、queryset物件的基本操作

#取出資料表中所有的資料, 返回queryset物件。
#注:資料量很大的時候,不要使用,否則記憶體會稱爆。
author_queryset = Author.objects.all()

#查詢資料庫中authorName 等於 “小明”的所有資料,返回queryset物件。
author_queryset = Author.objects.filter(authorName = "小明")

#查詢資料庫中authorName 不等於 “小明”的所有資料。
author_queryset = Author.objects.exclude(authorName = "小明")

#批量更新queryset中的所有物件, 接收 任意關鍵字引數
author_queryset.update(authorName = "小李", age = 10)
author_queryset.update(**{"authorName" :"小李", "age" :10})
print(author_queryset)
<QuerySet [<Author: RxSclass object (1)>, <Author: Author object (2)>, ....]>
#包含多個Author物件的可迭代。

for author_obj in author_queryset:
    print(author_obj)
<Author: Author object (1)>
<Author: Author object (2)>

三、欄位的常用查詢

#大於等於小於
Author.objects.filter(age__gt = 10)			#查詢年齡大於10的
Author.objects.filter(age__gte = 10)		#大於等於
Author.objects.filter(age__lt = 10)			#小於
Author.objects.filter(age__lte = 10)		#小於等於

#查詢 age 在 10-20中的資料
Author.objects.filter(age__range = [10, 20])

#查詢 age 在 可迭代物件中 的所有資料
Author.objects.filter(age__in = [1, 2, 3, 4])

#查詢 authorName 中包含 “T” 字母的資料
Author.objects.filter(authorName__contains = "T")	#大小寫不敏感
Author.objects.filter(authorName__icontains = "T")	#大小寫敏感匹配

#查詢 authorName以 “小” 字開始的資料
Author.objects.filter(authorName__startswith = "小")
Author.objects.filter(authorName__istartswith = "小")

#查詢 authorName以 “紅” 字結尾的資料
Author.objects.filter(authorName__endswith = "紅")
Author.objects.filter(authorName__iendswith = "紅")

四、QuerySet 的常用方法

注:呼叫以下方法都返回 QuerySet 物件

author_queryset = Author.objects.filter(authorName = "小明")

#索引和切片。該方法對應資料庫的limit查詢。
author_queryset[0]
author_queryset[0:10]

#返回 queryset 中的第一條、最後一條資料物件。
author_queryset.first()
author_queryset.last()

#返回queryset的長度。
author_queryset.count()

#根據 authorId 欄位排序:升序、降序
author_queryset.order_by('authorId')
author_queryset.order_by('-authorId')

#查詢出 需要的欄位 
#values方法的每個物件以dict形式返回
#values_list方法的每個物件以tuple形式返回
author_queryset.values('authorId', "authorName")
author_queryset.values_list('authorId', "authorName")

#根據authorName去重查詢
author_queryset.values("authorName").distinct()

#根據authorName分組、查詢每一組的數量。
from django.db.models import Count,Max,Min,Avg,Sum,Value
author_queryset.values("authorName").annotate(authorCount = Count("authorId"))


from django.db.models.functions import Upper,Lower,Left,Right,Substr,Concat
#常用方法
"""
Upper、Lower 大小寫
Left、Right  左右切片字串,接收索引長度引數
Substr		 擷取字串,接收 起始值和擷取長度
Concat		 拼接多個字串
"""
author_queryset.values(Upper("authorName"))
Left("authorName", 5)
Substr("authorName", 2)
#必須拼接都是字串的欄位
Concat( "sex", "authorName")
Concat( Value("你好啊,"), "authorName")   


from django.db.models import Q,F
"""
Q:可以對查詢方法進行封裝
“|” 和 “&” 表示 “or”和“and”
“~”表示 not取反
"""
author_queryset = Author.object.filter(Q(age = 18) | Q(authorId__gt = 10))
author_queryset = Author.object.filter(Q(age = 18) & ~Q(authorId__gt = 10))

"""
F : 查詢資料後,把資料 放在記憶體之後進行的操作
"""
author_queryset.values(F("age") + 1)

五、時間欄位的查詢


"""
range、in、gt、lt、gte、lte 方法和上邊的查詢對應

year、month、day、hour、minute、second、week_day   年月日、時分秒、周

isnull  查詢欄位為 空的資料, 適用於所有型別的欄位。
"""
book.object.filter(publicTime__second = 10)

六、外來鍵的關聯查詢

book_obj = book.object.get(pk = 1)
book_queryset = book.object.filter(publicTime__second = 10)

#使用values、或者values_list方法時候
book_queryset.values(authorName = F("authorId__authorName"), "bookId", "bookName")

#直接呼叫屬性, 返回 Author的例項物件
book_obj.authorId
book_obj.authorId.authorName

#查詢 author 物件 釋出的所有書籍
author_obj = Author.object.filter(pk = 1)
author_obj.book_set.all() #類名轉小寫,後邊加_set
#也可以使用book的filter來查詢
book.object.filter(authorId = author_obj)