0

Django: Remove Duplicates Filter for Related Posts.

  1. In yourapp/models.py
class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    tags = models.ManyToManyField('Tag')  
  1. In yourapp/views.py
class DetailPostView(generic.DetailView):
    model = Post
    template_name = 'blog/blog_detail.html'
    def get_context_data(self, **kwargs):
        context_data = super(DetailPostView, self).get_context_data(**kwargs)
        related_posts = Post.objects.filter(
            tags__in=list(self.object.tags.all())
        ).exclude(id=self.object.id).distinct()
        context_data['related_posts'] = related_posts[:5]  # limit for post
        return context_data  
  1. In yourapp/templates/yourapp/detail.html
{% for post in related_posts %}
  {{ post.title }}
{% empty %}
  No related post!
{% endfor %}

Hope it usefull.

solution tricks django python problem

Your Answer

blog comments powered by Disqus