Simple count of the number of records in the 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) 

I think I'm missing something really obvious, but how do I calculate the number of entries created in this many-to-many table authors = models.ManyToManyField(Author) ?

+8
django django-queryset many-to-many
source share
1 answer

Check out the docs , it's pretty simple:

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

Update:

The initial question asked a list of all authors in the database, not looking for a list of authors in each book.

To get a list of all authors in the database:

 Author.objects.count() ## Returns an integer. 
+11
source share

All Articles