基本的 Django DB 查詢

Django ORM 是一個功能強大的抽象,它允許你從資料庫中儲存和檢索資料,而無需自己編寫 SQL 查詢。

我們假設以下模型:

class Author(models.Model):
   name = models.CharField(max_length=50)

class Book(models.Model): 
   name = models.CharField(max_length=50)
   author = models.ForeignKey(Author)

假設你已將上述程式碼新增到 django 應用程式並執行 migrate 命令(以便建立資料庫)。啟動 Django shell

python manage.py shell

這啟動了標準的 python shell,但匯入了相關的 Django 庫,因此你可以直接關注重要部分。

首先匯入我們剛剛定義的模型(我假設這是在檔案 models.py 中完成的)

from .models import Book, Author

執行你的第一個選擇查詢:

>>> Author.objects.all() 
[]
>>> Book.objects.all()
[]

讓我們建立一個作者和書籍物件:

>>> hawking = Author(name="Stephen hawking")
>>> hawking.save()
>>> history_of_time = Book(name="history of time", author=hawking)
>>> history_of_time.save()

或使用 create function 建立模型物件並儲存在一行程式碼中

>>> wings_of_fire = Book.objects.create(name="Wings of Fire", author="APJ Abdul Kalam")

現在讓我們執行查詢

>>> Book.objects.all()
[<Book: Book object>]
>>> book = Book.objects.first() #getting the first book object
>>> book.name
u'history of time'

讓我們在 select 查詢中新增一個 where 子句

>>> Book.objects.filter(name='nothing')
[]
>>> Author.objects.filter(name__startswith='Ste')
[<Author: Author object>]

獲取有關給定書籍作者的詳細資訊

>>> book = Book.objects.first() #getting the first book object
>>> book.author.name # lookup on related model
u'Stephen hawking'

獲得 Stephen Hawking 出版的所有書籍(作者查閱書)

>>> hawking.book_set.all()
[<Book: Book object>]

_set 是用於反向查詢的符號,即當查詢欄位在 Book 模型上時,我們可以在作者物件上使用 book_set 來獲取他/她的所有書籍。