Drf: Getting related posts by ManyToMany category and a tags field
I'm trying to get all related posts by getting the id of the current post and filtering through the DB to find posts that are either in a similar category or have similar tags.
this is the model for the posts:
class Post(models.Model):
....
author = models.ForeignKey(
"users.User", on_delete=models.CASCADE, related_name='blog_posts')
tags = TaggableManager()
categories = models.ManyToManyField(
'Category')
....
status = models.IntegerField(choices=blog_STATUS, default=0)
def __str__(self):
return self.title
this is the views.py file:
class RelatedPostsListAPIView(generics.ListAPIView):
serializer_class = PostsSerializer
queryset = BlogPost.objects.filter(
status=1)[:5]
model = BlogPost
def get(self, pk):
post = self.get_object(pk)
qs = super().get_queryset()
qs = qs.filter(
Q(categories__in=post.categories.all()) |
Q(tags__in=post.tags.all())
)
return qs
with this code I get a RelatedPostsListAPIView.get() got multiple values for argument 'pk' error, I don't think I am actually getting the object with the id, any help would be much appreciated.
You also have to capture request in get(), so change:
class RelatedPostsListAPIView(generics.ListAPIView):
def get(self, pk):
# ...
to:
class RelatedPostsListAPIView(generics.ListAPIView):
def get(self, request, pk):
# ^^^ Add this