搜尋

了解 Django ORM

Oct 08, 2024 pm 08:11 PM

Understanding Django ORM

什麼是 ORM?

物件關聯映射(ORM)是 Django 中的一項功能,它允許我們使用 Python 程式碼與資料庫交互,而無需編寫 SQL 查詢。 ORM 在底層將 CRUD 操作轉換為 SQL,因此可以輕鬆建立、擷取、更新和刪除資料庫物件。

使用 ORM

在 Django 中,模型類別代表資料庫表,該類別的實例代表表中的一筆記錄。

每個模型至少有一個Manager,稱為物件。我們可以透過這個管理器從資料庫中檢索記錄,從而產生一個 QuerySet

查詢集是惰性的,這表示在明確請求之前不會取得結果。

常用的 QuerySet 方法
filter():檢索符合特定條件的記錄。
all(): 檢索所有記錄。
order_by():根據特定欄位對記錄進行排序。
unique():傳回唯一記錄。
annotate():為每筆記錄新增聚合值。
aggregate():從查詢集中計算一個值。
defer():僅載入模型的某些字段,延遲其他字段。

進階 ORM 功能

Q 和 F 物件 允許複雜的查詢和高效的資料庫層級操作。對於涉及 OR 條件的查詢,我們可以使用“Q”,而“F”則允許您在查詢中直接引用模型欄位。

from django.db.models import Q, F

# Using Q to filter published posts or created after a specific date
posts = Post.objects.filter(Q(status='published') | Q(created_at__gte='2024-01-01'))

# Using F to compare fields within a model (e.g., for a discount calculation)
class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    discounted_price = models.DecimalField(max_digits=10, decimal_places=2)

# Retrieve products where discounted price is less than price
discounted_products = Product.objects.filter(discounted_price__lt=F('price'))

查詢表達式(引用模型欄位)和資料庫函數(應用類似SQL的函數)都允許我們在資料庫層級執行操作,而不是將資料拉入Python進行處理。這有助於優化查詢並減少資料庫負載。

from django.db.models import Count, Max

# Count the number of posts for each status
status_count = Post.objects.values('status').annotate(count=Count('id'))

# Get the latest created post
latest_post = Post.objects.aggregate(latest=Max('created_at'))

自訂管理器讓我們新增額外的管理器方法或修改管理器最初傳回的查詢集。

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(status='published')

class Post(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    status = models.CharField(max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = models.Manager()  # Default manager
    published = PublishedManager()  # Custom manager for published posts

# Use the custom manager to get published posts
published_posts = Post.published.all()

ContentType 是一個模型,可用於在模型之間建立通用關係,而無需使用直接外鍵指定它們。常見用例包括需要附加到不同類型模型的註釋或標籤。

from django.contrib.contenttypes.models import ContentType

# Example model for comments
class Comment(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    text = models.TextField()

# Creating a comment for a Post instance
post = Post.objects.get(id=1)
comment = Comment.objects.create(
    content_type=ContentType.objects.get_for_model(Post),
    object_id=post.id,
    text='Great post!'
)

交易將資料庫操作捆綁為一個單元,確保資料一致性。我們可以使用 @transaction.atomic 裝飾器或 transaction.atomic() 上下文管理器將程式碼包裝在事務區塊中。

from django.db import transaction

# Using a transaction block
with transaction.atomic():
    post = Post.objects.create(title='New Post', content='Content here...', status='published')
    # Any other database operations will be part of this transaction

Django 允許在需要彈性的情況下執行原始 SQL 查詢 進行複雜查詢。但需謹慎使用。

from django.db import connection

def get_published_posts():
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM blog_post WHERE status = %s", ['published'])
        rows = cursor.fetchall()
    return rows

結論

Django 的 ORM 透過提供用於處理模型、管理器和查詢的高階 API 來簡化資料庫互動。了解和利用這些功能可以大大提高您的工作效率和應用程式的效能。

以上是了解 Django ORM的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的執行模型:編譯,解釋還是兩者?Python的執行模型:編譯,解釋還是兩者?May 10, 2025 am 12:04 AM

pythonisbothCompileDIntered。

Python是按線執行的嗎?Python是按線執行的嗎?May 10, 2025 am 12:03 AM

Python不是嚴格的逐行執行,而是基於解釋器的機制進行優化和條件執行。解釋器將代碼轉換為字節碼,由PVM執行,可能會預編譯常量表達式或優化循環。理解這些機制有助於優化代碼和提高效率。

python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:對於循環,最完整的指南Python:對於循環,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

python concatenate列表到一個字符串中python concatenate列表到一個字符串中May 09, 2025 am 12:02 AM

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器