python - 博士 : Getting related posts by ManyToMany category and a tags field

标签 python django django-rest-framework

我试图通过获取当前帖子的 ID 并通过数据库进行过滤来查找属于相似类别或具有相似标签的帖子来获取所有相关帖子。

这是帖子的模型:

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

这是views.py文件:

class RelatedPostsListAPIView(generics.ListAPIView):
    serializer_class = PostsSerializer
    queryset = BlogPost.objects.filter(
        status=1)[:5]
    model = BlogPost

def get_context_data(self, **kwargs):
    context = super(RelatedPostsListAPIView,
                    self).get_context_data(**kwargs)
    pk = self.kwargs['pk']
    main_post = BlogPost.objects.get(pk=pk)

    related_posts = main_post.filter(
        Q(categories__in=main_post.categories.all()) |
        Q(tags__in=main_post.tags.all())).exclude(pk=pk)[:5]

    context['related_posts'] = related_posts
    return context

这是序列化器

    class CategoriesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = ['id', 'title', 'slug']


class PostsSerializer(TaggitSerializer, serializers.ModelSerializer):
    categories = CategoriesSerializer(many=True)
    author = UserSerializer()
    tags = TagListSerializerField()
    cover = serializers.SerializerMethodField('get_image_url')

    class Meta:
        model = BlogPost
        fields = [
            "id",
            "title",
            "slug",
            "author",
            "description",
            "content",
            "tags",
            "categories",
            "keywords",
            "cover",
            "created_on",
            "updated_on",
            "status",
        ]

    def get_image_url(self, obj):
        request = self.context.get("request")
        return request.build_absolute_uri(obj.cover.url)

网址模式:

urlpatterns = [
    path('all/', PostsListAPIView.as_view(), name="all_posts"),
    path('recent/', RecentPostsListAPIView.as_view(), name="recent_posts"),
    path('related/<int:pk>/', RelatedPostsListAPIView.as_view(), name="related_posts")
]

使用这段代码,我得到一个 RelatedPostsListAPIView.get() gets multiple values for argument 'pk' 错误,我不认为我实际上得到了带有 id 的对象,任何帮助都是非常感谢。

最佳答案

您还必须在 get() 中捕获request,因此请更改:

class RelatedPostsListAPIView(generics.ListAPIView):
    def get(self, pk):
        # ...

至:

class RelatedPostsListAPIView(generics.ListAPIView):
    def get(self, request, pk):
        #         ^^^ Add this

关于python - 博士 : Getting related posts by ManyToMany category and a tags field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71930519/

相关文章:

javascript - 从页面中提取启用 JavaScript 的数据

django - 在 Gunicorn 超时时转储 Django 堆栈跟踪

python - Django-Rest-Framework:我可以使用两种不同的方法(具有相同的 url_path 但不同的请求方法)创建 View 集吗?

python - Django Rest Framework 中没有 View 或模型的简单 Web API

django-rest-framework - 使用djangorest框架,如何为现有父对象添加新的嵌套子对象

Python:延迟函数调用的装饰器

python - 键盘中断与 python 的多处理池和映射函数

python - 如何将 Marshall 代码对象转换为 PYC 文件

python - TypeError 强制转换为 Unicode : need string or buffer

python - Django 模型序列化器