Let's say I have these:
class Publication(models.Model):
title = models.CharField(max_length=128)
author = models.ManyToManyField(Author, through='Authorship')
class Author(models.Model):
first_name = models.CharField(db_index=True, max_length=64)
last_name = models.CharField(db_index=True, max_length=64)
How can I get ALL the publications AND their author(s) in one query. I want to list each publication and its authors on a page. But I don't want to hit the authors table for every publication.
The only way I know to do it is with select_related
in the view and authorship_set.all()
on the template. But that's one query for every publication. I could easily do it with raw sql, but that's yucky.
*BTW, I'm using the through model because I have to keep some extra data in there, like author_display_order
.
EDIT:
Turns out authorship_set
was doing all the querying.
When I run it this way from console only one query gets fired:
pubs = Publication.objects.all().prefetch_related('author')
for p in pubs:
print p.title
for a in p.author.all():
print a.last_name