13

Possible Duplicate:
A left outer reverse select_related in Django?

A BlogPost has many Comments. I want to get a list of BlogPosts and all their comments.

Thus, I have

BlogPost.objects.filter(my_filter).select_related()

But the ForeignKey is on the Comment, not the BlogPost, so the select_related() doesn't prefetch any comments. Is there a way to get this to work?

I can't reverse the query (Comment.objects...) because then the other objects that the select_related() does fetch wouldn't work. I need it to work both ways.

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

-1

Why won't you fetch the comments and then use regroup template tag to display them:

# Select all Comments with BlogPost data - one query
comments = Comment.objects.select_related('blog_post').order_by('-blog_post').all()

Then in template:

{% regroup comments by blog_post as posts %}
{% for blog_post in posts %}

    <p>Blog post {{ blog_post.title }}</p>
    <ul>
    {% for comment in blog_post.comments %}
    ...
    {% endfor %}
    </ul>
    </p>
{% endfor %}
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
  • 2
    I think because of my last paragraph. `BlogPost` has other foreign keys that `select_related` *does* work on, and I want it to continue working on those. By fetching the comments first you're just shifting the problem. – mpen Jan 30 '12 at 21:37
  • 6
    Another problem with this solution is that it won't get blog posts with no Comments – Ben G Feb 16 '12 at 22:03