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)
中创建的记录数量的计数?
查看文档,非常简单:
b = Book.objects.all()[0]
b.authors.count()
更新:
最初的问题是要求数据库中所有作者的列表,而不是寻找每本书的作者列表。
获取数据库中所有作者的列表:
Author.objects.count() ## Returns an integer.