python – Django ORM每位作者的书籍数量

class Author(models.Model):
   name = models.CharField(max_length=100)
   age = models.IntegerField()
   friends = models.ManyToManyField('self', blank=True)

class Publisher(models.Model):
   name = models.CharField(max_length=300)
   num_awards = models.IntegerField()

class Book(models.Model):
   isbn = models.CharField(max_length=9)
   name = models.CharField(max_length=300)
   pages = models.IntegerField()
   price = models.DecimalField(max_digits=10, decimal_places=2)
   rating = models.FloatField()
   authors = models.ManyToManyField(Author)
   publisher = models.ForeignKey(Publisher)
   pubdate = models.DateField()

class Store(models.Model):
   name = models.CharField(max_length=300)
   books = models.ManyToManyField(Book)

我想知道有多少本书是针对作者注册的.
比方说,我有作者A1,A2,A3.

一本书可能属于多位作者.
我有书,B1,B2,B3

我想知道有多少作者A1的书.让我说他属于2本书.

已经尝试过

Author.objects.all()
Books.objects.filter(authors=43).count()
2

哪一个更好?

for auth in authors:
  book.count =book.book_auths.count()
  book_counts_alternative_way = Book.objects.annotate(num_count=Count('book_auths')).filter(book_auths=tech, num_count__gt=0)

还有其他很有效的方法吗?

最佳答案 将related_name提供给

authors = models.ManyToManyField(Author, related_name='book_auths')

然后

author = Author.objects.get(id=43)
auth_books = author.book_auths.all()

#auth_books are all books which belong to one author

要么

author = Author.objects.get(id=43)  
books = Book.objects.filter(author=author) 

将给出作者所属的所有书籍.

或者如果你想知道所有作者

authors = Authors.objects.all()
books = Book.objects.filter(author__in=(x for x in authors))

为您提供所有在db中存在作者的书籍.

要知道多少:只需将.count()附加到结果查询集.

点赞