从django模型中的多个字段中获取值?
我得去吃饭从django模型中的多个字段中获取值?,django,Django,我得去吃饭 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
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
***一本书有许多作者作者是多对多的,因此您需要嵌套另一个循环。您创建的
作者
对象类似于列表,例如:
for unit_sale in Unitary_sale.objects.all():
for x in author:
by_authors[x] = ....
编辑:实际上,我注意到您在创建作者
时犯了一个错误。应该是:
author = unit_sale.book.authors.all()
然后,您可以使用for循环迭代上述所有Author对象。authors是多对多的,因此您需要嵌套另一个循环。您创建的
作者
对象类似于列表,例如:
for unit_sale in Unitary_sale.objects.all():
for x in author:
by_authors[x] = ....
编辑:实际上,我注意到您在创建作者
时犯了一个错误。应该是:
author = unit_sale.book.authors.all()
然后,您可以使用for循环来迭代上述所有Author对象。请注意在后台执行的db查询的数量。在我的代码中,访问和迭代db关系的简单方法让我大吃一惊,每一个页面产生约900个db查询。请注意在引擎盖下执行的db查询数量。在我的代码中,访问和迭代db关系的简单方法让我大吃一惊,每一个页面产生约900 db的查询。好吧,到目前为止你有什么,它如何工作?好吧,到目前为止你有什么,它如何工作?你可以添加与预加载查询集相关的.prefetch\u。可以添加与预加载查询集相关的.prefetch\u。Uniunity_sale.objects.all().prefetch_related('authors'))