title: Django blog - calling latest 3 posts per category via many to many
body: <p>So far my blog project has :</p>
  
  <blockquote>
    <p>Models.py</p>
  </blockquote>
  
  <pre><code> class Category(models.Model):
          title = models.CharField(max_length=200)
  
      def __str__(self):
          return self.title
  
      class Meta:
          verbose_name_plural = "categories"
  
  
  class Post(models.Model):
          title = models.CharField(max_length=200)
          summary = models.CharField(max_length=500, default = True)
          body = models.TextField()
          pub_date = models.DateTimeField(default=timezone.now)
          categories = models.ForeignKey('Category', default=True)
  
  
          def __str__(self):
              return self.title
  </code></pre>
  
  <blockquote>
    <p>Views</p>
  </blockquote>
  
  <pre><code>from django.shortcuts import render
  from .models import Post, Category
  
  def getAllCategories(request):
      categories = Category.objects.all()
  
      context = {
          'categories':categories,
              }
  
      return render(request, 'categories/getAllCategories.html', context)
  </code></pre>
  
  <blockquote>
    <p>Template </p>
  </blockquote>
  
  <pre><code> {% extends "../posts/base.html" %}
  
  {% block content %}
      &lt;div&gt;
          {% for category in categories %}
              &lt;div&gt;
                  &lt;h3&gt;{{ category.title }}&lt;/h3&gt;
                  &lt;ul&gt;
                  {% for post in category.post_set.all %}
                      &lt;li&gt;&lt;a href=#&gt;{{post.title}}&lt;/a&gt;&lt;/li&gt; 
                          - {{post.summary}}
                  {% endfor %}
                  &lt;/ul&gt;
              &lt;/div&gt;
          {% endfor %}
      &lt;/div&gt;
  {% endblock %}
  </code></pre>
  
  <p>This pulls through all of my posts per category fine - however I'm stuck as I would like to only pull through the latest three posts per category. I understand that in a simple view you can use order_by()[:3], but then you can't use post_set with that. So I need a way of filtering by top three posts within a category, so using the many-to-many relationship. Hope this is clear.</p>
  
  <p>Many thanks</p>