简单统计ManyToMany表中的记录数

发布于 2024-11-19 12:16:13 字数 871 浏览 0 评论 0原文

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏有森光若流苏 2024-11-26 12:16:13

查看文档,它非常简单:

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文