pythondjangodjango-taggit

Taggit Django - Return View of Posts Based on User Post Tags)


I have recently been playing around Taggit. I have managed to filter my Posts model, based on different Tags by adding the following filter .filter(tags__name__in='categoryone').

Although, would anyone be able to provide me with guidance on how to filter my Posts based on the tags my user has already used within his or her previous posts?

So for example, if my user has previously created a Post within the "categoryone" tag, all the posts he or she would see on their Post Feed would be tags relevant to "categoryone" but he or she wouldn't see any posts within "categorytwo" or "categorythree" unless he or she makes a post within either or both of those categories.

I was hoping something such as .filter(tags=self.request.user) would work, but this is throwing a Tag Instance error. Ideally I'm wanting to add a filter which filters through the existing tags my user has used within their previous posts.

Any examples would be greatly appreciated! :-)

Thanks!

--

Views.py (Query for PostListView)

  def get_queryset(self):
        user = self.request.user
        tags = Tag.objects.filter(post__author=user)

        qs = Follow.objects.filter(user=user)
        qa = Tag.objects.filter(post__author=user)
        follows = [user]
        tags = [user]
        for obj in qs:
            follows.append(obj.follow_user)
        for obj in qa:
            obj.user = self.request.user
        return Post.objects.filter(author__in=follows).filter(author__in=tags).order_by('-date_posted')

Models.py

class Post(models.Model):
    content = models.TextField(max_length=1000)
    date_posted = models.DateTimeField(default=timezone.now)
    image = models.ImageField(default='default.png', upload_to='srv_media')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    likes= models.IntegerField(default=0)
    dislikes= models.IntegerField(default=0)
    tags = TaggableManager()


Solution

  • Trying to give an answer based on your current work:

    def get_queryset(self):
            user = self.request.user
            tags = Tag.objects.filter(post__author=user)
    
            qs = Follow.objects.filter(user=user)
            qa = Tag.objects.filter(post__author=user)
            follows = [user]
            tags = [user] 
            for obj in qs:
                follows.append(obj.follow_user)
            for obj in qa:
                tags.append(obj.post.author)
            return Post.objects.filter(author__in=follows).filter(author__in=tags).order_by('-date_posted')