Search code examples
djangocategoriessimilarity

Django Calculate Similar Posts Based On Categories Not Working


I want to calculate similar posts based on categories. This is what I have so far in models:

class Post(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, default=15)

    def get_related_posts_by_tags(self):
       category = get_object_or_404(Category, name=self.category.title)
       posts = Post.objects.filter(category=category)
       return posts

class Category(models.Model):
    name = models.CharField(max_length=250, unique=True)

And in my templates:

{% for posts in object.get_related_post_by_tag %}
   {{ posts.title }}
{% endfor %}

For whatever reason, this does not work, and in my template, I do not seen any posts with the same category. This is why I am wonder if I am doing it wrong, or if I have little problem I easily fix. Thanks for all help.


Solution

  • You can work with:

    class Post(models.Model):
        category = models.ForeignKey(Category, on_delete=models.CASCADE, default=15)
    
        def get_related_posts_by_tags(self):
           return Post.objects.filter(category_id=self.category_id)
    

    This will also prevent loading the Category object in memory if it is not used later on.

    You might want to exclude the current post, in that case, you can use:

    class Post(models.Model):
        category = models.ForeignKey(Category, on_delete=models.CASCADE, default=15)
    
        def get_related_posts_by_tags(self):
           return Post.objects.filter(
               category_id=self.category_id
            ).exclude(pk=self.pk)

    In your template there is also a typo: it is get_related_posts_by_tags, so _posts_, not _post_

    {% for posts in object.get_related_posts_by_tags %}
       {{ posts.title }}
    {% endfor %}