有沒有過濾預取對象的方法?我需要獲取最新的()預取對象,但prefetch_related不起作用,如果您使用最新的,因爲查詢被更改?Django中prefetch_related上的過濾器
這裏的例子做什麼,我需要,但我希望有一個簡單的解決辦法...
https://github.com/ionelmc/django-prefetch#example
有沒有過濾預取對象的方法?我需要獲取最新的()預取對象,但prefetch_related不起作用,如果您使用最新的,因爲查詢被更改?Django中prefetch_related上的過濾器
這裏的例子做什麼,我需要,但我希望有一個簡單的解決辦法...
https://github.com/ionelmc/django-prefetch#example
從Django 1.7開始,過濾預取對象是可能的。見this SO answer和the Django documentation。
這是非常簡單的方法,這與那些應用程序難以相比,但是希望你會發現它有用的:
class Author(models.Model):
name = models.CharField(max_length=100)
def latest_book(self):
return max(self.book_set.all(), key=lambda book: book.created)
authors = Author.objects.prefetch_related('book_set')
authors[0].latest_book() # what you wanted
是的,可以這樣做:
authors=Author.objects.prefetch_related('book_set')
如果你想通過一個屬性(名稱)來過濾出現在作者的模型,你可以簡單地通過書面形式將其過濾:
authors.filter(name='your_value')
但是,如果要在書籍模型上應用過濾器,則必須編寫以下方法:
authors.filter(book__created__gt='your_date')
這會將f ilter所有已創建日期(在Book模塊中創建的屬性)大於日期的圖書。
我測試了這個,它似乎生成與天真循環相同的查詢...我不認爲你可以使用select_related反向關係 – alan
我很抱歉 - 當然它應該prefetch_related(我編輯我的答案)。使用這個與all()設置的孔被prefetched並迭代它不應該擊中數據庫。 – jasisz