[Django]-How do you add similar posts to a detail page using django

3👍

you should let us know what is not matching.

your post_detail tries to find a Post with a tag’s slug.

instance = get_object_or_404(Post, slug=slug)

I doubt that’s what you intended.

get_object_or_404 either tries to find an exact match or raise error.
Since your original post has the tag, you will be getting the same post or multiple.

The following block of code is not what you said you wanted either.

        {% for tag in instance.tags.all %}
        <h4> <a href="{% url 'posts:detail' slug=tag.slug %}"> {{ tag.title }}</a>  </h4><hr>
        {% endfor %}

It lists all tags of the original post, doesn’t list related post (via tag)

If you want to show related post, and you intent to use tag to define relatedness, define a method in your post model to return such related posts.

def get_related_posts_by_tags(self):
    return Post.objects.filter(tags__in=self.tags.all())

are those videos there because they share similar tags?

Not sure how they judge the relatedness, you should ask that in a separate question.
If I have to guess, it would be more than just tag comparison though.

** edit

Actually, proper term for relatedness is similarity.

You might find further info by googling document similarity.

{% for post in instance.get_related_post_by_tag %}
// href to post.absolute_url
{% endfor %}
👤eugene

4👍

In the long run and to not reinvent the wheel using a reusable Django application already tried and tested is the sensible approach. In your case there is such app: django-taggit
and is easy to use:

  1. You install it

    pip install django-taggit
    
  2. Add it to your installed apps:

    INSTALLED_APPS = [
        ...
        'taggit',
    ]
    
  3. Add its custom manager to the model on which you want tags

    from django.db import models
    
    from taggit.managers import TaggableManager
    
    class YourModel(models.Model):
        # ... fields here
    
        tags = TaggableManager()
    

    and you can use it in your views:

    all_tabs = instance.tags.all()
    

It even has a similar_objects() method which:

Returns a list (not a lazy QuerySet) of other objects tagged similarly
to this one, ordered with most similar first.

EDIT

To retrieve similar posts you should use:

similar_posts = instance.tags.similar_objects()

and to get only the first, let’s say, 5 similar posts:

similar_posts = instance.tags.similar_objects()[:5]

where instance is a instance of the Post model.

👤doru

Leave a comment