代码之家  ›  专栏  ›  技术社区  ›  tree em

从Django模型中的manytomany字段获取值?

  •  0
  • tree em  · 技术社区  · 15 年前

    我得吃饭了

    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 回复  |  直到 15 年前
        1
  •  1
  •   Ellie P.    15 年前

    作者是多对多的,所以您需要嵌套另一个循环。这个 author 像列表一样制作的对象,例如:

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

    编辑 :事实上,我注意到你在如何创造 作者 . 应该是:

    author = unit_sale.book.authors.all()
    

    然后您可以使用for循环遍历上面提到的所有author对象。

        2
  •  2
  •   fest    15 年前

    只需注意在引擎盖下执行的DB查询的数量。我被我的代码中访问和迭代数据库关系的简单方法催眠了,这导致每个 页。