2016-09-29 103 views
0

說我有Django模型,像這樣:Django的聚合多對多領域

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

class Book(models.Model): 
    authors = models.ManyToManyField(Author) 

什麼是得到一個或兩個查詢中每本書作者創造的(最好是有序的)的數量的最好方法?

作者集可能會相當大,所以我正在尋找一種方法來避免遍歷所有它。

模型中的圖書添加

回答

-2

...

... 
author = models.ForeignKey(Author) 
... 

,並獲得然後使用一個QuerySet像

... 
Author.objects.get(id=some_id).book_set.all() # this line, return all book of these author, if you want get the number just add at end '.count()' 
... 
+0

你沒有回答這個問題 - you're改變他的模型。 – brianpck

+0

是一樣的...你可以做到與你的關係模型一樣,重要的是...... ... book_set.all()' –

+0

這是真的,但實際上我希望有一種方法可以在查詢中執行此操作或兩個),而不是迭代所有選項,因爲作者集可能會相當大。我會澄清我的問題。謝謝! –