[Django]-How to use django-taggit similar_objects() with Class-based views

6👍

You could build your view this way:

class GameDetail(DetailView):
    model = Game
    template_name = 'core/game_detail.html'
    context_object_name = 'game_detail'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["related_items"] = self.object.tags.similar_objects()[:4]
        return context

Then you can use the related_items list on your template, like you normally do.

Note: if you are using python2 the super call should be this one:

context = super(self, GameDetail).get_context_data(**kwargs)
👤dethos

Leave a comment