2010-01-17 58 views
0

我有表從django模型中的manytomany字段獲取值?

class Book(models.Model): 
    title = models.CharField(max_length=200)   
    authors = models.ManyToManyField(Individual, related_name="author_for", blank=True, null=True) 
    illustrators = models.ManyToManyField(Individual, related_name="illustrator_for", blank=True, null=True) 

class Unitary_Sale(models.Model):   
      book = models.ForeignKey(Book) 
      quantity = models.IntegerField() 
      unit_price = models.DecimalField(max_digits=15, decimal_places=3) 
      sale = models.ForeignKey(Sale) 

如何報告書已被作者或插畫出售?

by_author = {} 
    for unit_sale in Unitary_sale.objects.all(): 
     author = unit_sale.book.authors 
     by_authors[author] = (unit_sale.quantity, unit_sale.quantity *unit_sale.unit_price) 


Author Qty Amount($) 
A  2  20 
A&B  3  30 

***一本書有許多作者

+2

那麼,你到目前爲止有什麼,它怎麼不工作? – 2010-01-17 06:31:59

回答

1

作者是多到很多,所以你需要嵌套另一個循環。你像一個列表中所做的author對象,如:

for unit_sale in Unitary_sale.objects.all(): 
    for x in author: 
     by_authors[x] = .... 

編輯:其實,我注意到你如何創建author一個錯誤。它應該是:

author = unit_sale.book.authors.all() 

然後,您可以使用for循環遍歷所有Author對象,如上所述。

2

只要注意在引擎蓋下執行的db查詢的數量。我被催眠的簡單方法來訪問和遍歷數據庫關係在我的代碼導致〜900分貝查詢一個頁面。

相關問題