1

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
Rob L
  • 3,634
  • 2
  • 19
  • 38
  • 1
    Have you tried `prefetch_related`? – thebjorn Jul 16 '14 at 18:51
  • I have, but `authorship_set.all()` still hits the db. – Rob L Jul 16 '14 at 18:53
  • 1
    That seems strange... you'll need to post your code if you'd like more helpful suggestions. You can always read the Publication and Author models in two queries and combine them manually.. – thebjorn Jul 16 '14 at 18:56
  • I think I have it. `authorship_set.all()` is the wrong way. Using `author.all()` seems to do right. I'll edit the question to reflect my findings. – Rob L Jul 16 '14 at 19:01

0 Answers0