ManyToMany表中记录数的简单计数

时间:2011-07-11 17:05:52

标签: django many-to-many django-queryset

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)中创建的记录数?

1 个答案:

答案 0 :(得分:11)

查看the docs,这非常简单:

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

<强>更新

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

获取数据库中所有作者的列表:

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