? ??
概要
Django的對象關(guān)系映射器(ORM)是其核心功能之一,允許開發(fā)者使用Python代碼來定義、操作和查詢數(shù)據(jù)庫。這篇文章將帶你深入了解Django ORM的強大之處,從基本概念到高級查詢技巧,提供豐富的示例幫助你掌握使用Django ORM進行有效和高效的數(shù)據(jù)庫操作。
1. Django ORM基礎(chǔ)
Django ORM的目的是提供一種簡單的方法用來:
-
將復(fù)雜的SQL查詢轉(zhuǎn)換為Python代碼
-
保護項目免受SQL注入攻擊
-
提供數(shù)據(jù)庫后端的獨立性
定義模型
在Django中,每個數(shù)據(jù)庫表由一個Python類表示,這個類繼承自django.db.models.Model
。
from?django.db?import?models
class?Author(models.Model):
????name?=?models.CharField(max_length=100)
????age?=?models.IntegerField()
????def?__str__(self):
????????return?self.name
進行數(shù)據(jù)庫遷移
定義模型后,使用makemigrations
和migrate
命令創(chuàng)建或更新數(shù)據(jù)庫結(jié)構(gòu)。
python?manage.py?makemigrations
python?manage.py?migrate
2. 創(chuàng)建記錄
使用模型的構(gòu)造函數(shù)創(chuàng)建新記錄。
new_author?=?Author(name='J.K.?Rowling',?age=54)
new_author.save()
使用create
方法
可以使用模型管理器的create
方法更快捷地創(chuàng)建記錄。
Author.objects.create(name='George?R.R.?Martin',?age=71)
3. 讀取記錄
Django ORM提供了豐富的API來查詢數(shù)據(jù)庫。
獲取所有記錄
authors?=?Author.objects.all()
獲取單個記錄
author?=?Author.objects.get(name='J.K.?Rowling')
過濾記錄
young_authors?=?Author.objects.filter(age__lt=50)
排除特定記錄
old_authors?=?Author.objects.exclude(age__lt=50)
4. 更新記錄
更新記錄就像修改任何其他Python對象。
author?=?Author.objects.get(name='J.K.?Rowling')
author.age?=?55
author.save()
批量更新
Author.objects.filter(age__lt=50).update(age=50)
5. 刪除記錄
刪除記錄也很直接。
author?=?Author.objects.get(name='J.K.?Rowling')
author.delete()
批量刪除
Author.objects.filter(age__gt=70).delete()
6. 高級查詢操作
Django ORM的真正威力在于它的查詢能力。
關(guān)聯(lián)查詢
class?Book(models.Model):
????title?=?models.CharField(max_length=200)
????author?=?models.ForeignKey(Author,?on_delete=models.CASCADE)
books?=?Book.objects.filter(author__name='J.K.?Rowling')
聚合查詢
from?django.db.models?import?Avg
average_age?=?Author.objects.all().aggregate(Avg('age'))
使用Q對象進行復(fù)雜查詢
from?django.db.models?import?Q
authors?=?Author.objects.filter(Q(age__gt=50)?|?Q(name__startswith='J'))
7. 數(shù)據(jù)庫函數(shù)和表達式
Django ORM還允許開發(fā)者在查詢中使用數(shù)據(jù)庫函數(shù)。
使用F
表達式比較字段值
from?django.db.models?import?F
authors?=?Author.objects.filter(age__gt=F('age')?-?10)
使用注解添加臨時字段
from?django.db.models?import?Count
books?=?Book.objects.annotate(num_authors=Count('author'))
8. ORM的優(yōu)化
大型項目中,ORM的性能變得尤其重要。
使用select_related
和prefetch_related
減少數(shù)據(jù)庫查詢次數(shù)。
#?select_related用于“一對一”和“多對一”關(guān)系
books?=?Book.objects.select_related('author')
#?prefetch_related用于“多對多”和“一對多”關(guān)系
authors?=?Author.objects.prefetch_related
('book_set')
延遲字段加載
使用only
和defer
來控制加載的字段。文章來源:http://www.zghlxwxcb.cn/news/detail-758893.html
Author.objects.defer('age')
結(jié)論
Django ORM提供了一個強大的抽象層來操作數(shù)據(jù)庫,使得開發(fā)者可以避免寫原生SQL并更專注于業(yè)務(wù)邏輯。通過這篇文章,你應(yīng)該對如何高效地使用Django ORM有了清晰的理解。不過,值得注意的是,ORM的使用并非沒有代價,有時它可能會隱藏性能問題,所以理解它的內(nèi)部工作原理對于優(yōu)化查詢和提升性能是至關(guān)重要的。在深入使用之前,閱讀官方文檔并深入了解Django ORM的工作方式是一個不錯的選擇。文章來源地址http://www.zghlxwxcb.cn/news/detail-758893.html
到了這里,關(guān)于Django ORM:數(shù)據(jù)庫操作的Python化藝術(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!