ManyToMany表中记录数的简单计数(Simple count of number of records in ManyToMany table)

编程入门 行业动态 更新时间:2024-10-28 08:24:19
ManyToMany表中记录数的简单计数(Simple count of number of records in ManyToMany table) 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)

我认为我错过了一些非常明显的东西,但是如何获得在此多对多表中authors = models.ManyToManyField(Author)创建的记录数?

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)

I think I'm missing something really obvious but how do I get a count for the number of records created in this many-to-many table authors = models.ManyToManyField(Author)?

最满意答案

看看这些文档 ,这很简单:

b = Book.objects.all()[0] b.authors.count()

更新:

最初的问题是要求列出数据库中所有作者的列表,而不是查找每本书的作者列表。

要获取数据库中所有作者的列表,请执行以下操作:

Author.objects.count() ## Returns an integer.

Check out the docs, it's pretty simple:

b = Book.objects.all()[0] b.authors.count()

Update:

The original question was asking for a list of all of the Authors in the database, not looking for a list of authors per book.

To get a list of all of the authors in the database:

Author.objects.count() ## Returns an integer.

更多推荐

本文发布于:2023-08-04 23:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423200.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   Simple   ManyToMany   count   table

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!