Django Aggregate ManyToMany fields
<p>Say I have Django models like so:</p>

<pre><code>class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    authors = models.ManyToManyField(Author)
</code></pre>

<p>What's the best way to get the the number of books each author created (preferably ordered) within a query or two?</p>

<p>The Author set might get pretty big, so I'm looking for a way to avoid iterating over all of it.</p>

<p>in your model book add...</p>

<pre><code>...
author = models.ForeignKey(Author)
...
</code></pre>

<p>and to get then you use a QuerySet like</p>

<pre><code>...
Author.objects.get(id=some_id).book_set.all() # this line, return all book of these author, if you want get the number just add at end '.count()'
...
</code></pre>

python django many-to-many