Search code examples
djangodjango-taggit

How to fetch related items when using taggit in django?


Using django-taggit, I'd like to fetch related posts which have the same tag(s) as the current post. Here is the views:

from taggit.managers import TaggableManager, TaggedItem
from taggit.models import Tag

def post(request, post_slug):

    post = Article.objects.get(slug = post_slug)
    comments = Comment.objects.filter(post=post)
    #tag = get_object_or_404(Tag, id= post.id)
    #related = Article.objects.filter(tags= post.tags.similar_objects()) 

    print "RELATED \n"   
    #print related

    d = dict(post=post, comments=comments, form=CommentForm(), 
             user=request.user)
    d.update(csrf(request))
    return render_to_response("article/post.html", d)

I looked at the docs and different answers (like this) but none worked for me. So appreciate your help.


Solution

  • post.tags.similar_objects() in and of itself will provide you with a list of the results you want (documentation here).