2010-01-17 94 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分贝查询一个页面。