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()附加到结果查询集.
总结以上是内存溢出为你收集整理的python – Django ORM每位作者的书籍数量全部内容,希望文章能够帮你解决python – Django ORM每位作者的书籍数量所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)