Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

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

like image 652
super9 Avatar asked Jul 11 '11 17:07

super9


1 Answers

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.
like image 154
Jack M. Avatar answered Oct 15 '22 03:10

Jack M.