如果你喜歡單的查詢和使用MySQL
,檢查由@Crazyshezy在他的評論提供the excellent link。
對於PostgreSQL
後端,一個可能的查詢(假設有非空的FK
關係從Book
到Author
和Author
到Category
):
SELECT * FROM (
SELECT book_table.*, row_number() OVER (PARTITION BY category_id ORDER BY RANDOM()) AS rn
FROM book_table INNER JOIN author_table ON book_table.author_id = author_table.id
) AS sq
WHERE rn <= 5
然後,您可以把它包裝一個RawQuerySet
內得到Book
實例
from collections import defaultdict
qs = Book.objects.raw("""The above sql suited for your tables...""")
collection = defaultdict(list)
for obj in qs:
collection[obj.category_id].append(obj)
categories_w_rand_books = []
for category in c:
categories_w_rand_books.append((category, collection[category.id]))
您可能不希望爲每個請求直接運行此查詢而無需進行某些緩存。
此外,你的代碼產生至多50 * 5 = 250 Book
S,隨機的,我只是不知道爲什麼,因爲它似乎過多,單頁。項目是否顯示爲選項卡或其他內容?也許你可以通過做Ajax來減少SQL的數量,或者簡化要求?
更新
要使用book.author
瓦特/ O觸發比另一個更查詢,嘗試prefetch_related_objects
from django.db.models.query import prefetch_related_objects
qs = list(qs) # have to evaluate at first
prefetch_related_objects(qs, ['author'])
# now instances inside qs already contain cached author instances, and
qs[0].author # will not trigger an extra query
上面的代碼預取作者在批次,並將它們填充到qs
。這只是增加了另一個查詢。
來源
2013-01-01 16:20:06
okm
不設法得到它在代碼方面,而是試圖監視數據庫... – 2012-12-31 02:49:49
更多的代碼可能是有用的(那是什麼'e'?)。你能否也請包括幾個重複的查詢? –
嘗試優化查詢(加入他們)並將結果保存到變量中... – Raptor