【问题标题】:get value from manytomany field in django model?从 django 模型中的 manytomany 字段中获取价值?
【发布时间】:2010-01-17 06:26:40
【问题描述】:

我必须要桌子

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

***一本书有多个作者

【问题讨论】:

  • 嗯,到目前为止你有什么,它是怎么工作的?

标签: django


【解决方案1】:

请注意在后台执行的数据库查询的数量。在我的代码中访问和迭代数据库关系的简单方法让我着迷,这导致每个 一个 页面约 900 个数据库查询。

【讨论】:

  • 您可以添加 .prefetch_related 来预加载查询集。 unitary_sale.objects.all().prefetch_related('authors')
【解决方案2】:

authors 是多对多的,因此您需要嵌套另一个循环。你创建的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 对象,如上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2020-07-07
    • 2013-05-12
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    相关资源
    最近更新 更多