加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:37:31 所属栏目:Python 来源:网络整理
导读: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.I
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()附加到结果查询集.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读