Django Viewset 检索不使用默认路由器

Django Viewset retrieve not working with Default Router

我正在尝试使用 Django 视图集中的检索方法访问特定评论。我正在使用默认路由器来路由我的网址。我可以在 api/posts/ 列出所有评论,但无法在 api/posts/1 获得一条评论。我收到一个类型错误:Field.init() 在尝试访问 URL 时得到了一个意外的关键字参数 'pk'。关于原因有什么想法吗?

urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from posts.views import PostsViewSet, CommentsViewSet

router = DefaultRouter()
router.register(r"comments", CommentsViewSet, basename='comments')

urlpatterns = [
    path("", include(router.urls)),
]
views.py
class CommentSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(label='commentID')
    comment = serializer.CharField()
    created_at = serializers.DateTimeField(required=False)
    updated_at = serializers.DateTimeField(required=False)
    posts = serializers.SerializerMethodField()

    class Meta:
        model = Comments
        # fields = "__all__"
        fields = ['id', 'comment','created_at', 'updated_at', 'posts']

        def to_representation(self, instance: Comment) -> dict:
            '''Pass for now'''
            ret = super().to_representation(instance)
            return ret

        def get_queryset(self) -> QuerySet:
            qs = Comment.objects.all()
            return qs

        def create(self, validated_data: dict) -> Comment:
            return Comment.objects.create(**validated_data)

        def update(self, instance: Comment, validated_data: dict) -> Comment:
            '''Pass post-validation errors silently'''
            for field in validated_data:
                setattr(instance, field, validated_data.get(
                    field, getattr(instance, field)))
            instance.save()
            return instance
class CommentViewSet(viewsets.ViewSet):
    def list(self, request):
        queryset = Comment.objects.all()
        result = CommentSerializer(queryset, many=True)
        if result:
            return Response(result.data)
        else:
            return Response(data=result.data, status=200)

    def retrieve(self, request, pk=None):
        queryset = Comment.objects.all()
        condition = get_object_or_404(queryset, pk=pk)
        result = CommentSerializer(queryset, pk=pk)
        print(result)
        return Response(result.data)

首先你没有在序列化器中使用条件对象。

第二个 drf 默认 pk 字段名称是 id 而不是 pk,在序列化期间不需要传递 pk process.Below 已更新检索方法,请检查相同。

def retrieve(self, request, pk=None):
        # queryset = Comment.objects.all() #no need as you are using get_object_or_404 to fetch single object
        condition = get_object_or_404(Comment, id=pk) #replaced pk by id here
        result = StudentSerializer(condition) #used condition in serializer
        print(result)
        return Response(result.data)