I Have to tables
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)
How can report book has been sold by aut开发者_高级运维hor or illustrator?
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
***one book has many author
Just be mindful about the number of db queries that are executed under the hood. I was hypnotized by the easy way to access and iterate over db relations in my code which resulted in ~900 db queries per one page.
authors is many-to-many, so you'll need to nest another loop. The author
object you made like a list, eg:
for unit_sale in Unitary_sale.objects.all():
for x in author:
by_authors[x] = ....
Edit: actually, I noticed a mistake in how you are creating author
. It should be:
author = unit_sale.book.authors.all()
Then you can use a for loop to iterate through all the Author objects as above.
精彩评论