在Django中的发布请求中从URL捕获值

时间:2019-08-22 04:42:09

标签: python django django-rest-framework

我想在发布请求中将URL值从URL捕获到我的视图中。

我的urls.py如下所示

从django.urls导入路径 来自。将视图导入为projects_views

urlpatterns = [
    path('<str:project_id>/comments', projects_views.ProjectCommentList.as_view(), name="project_comments"),
]

,我想在ListCreateAPIView中捕获值project_id。 拨打电话效果很好。

我的views.py如下所示

class ProjectCommentList(generics.ListCreateAPIView):
    queryset = projects_models.Comment.objects.all()
    serializer_class = projects_serializers.CommentSerializer


    def get(self, request, project_id=None):
        queryset = self.filter_queryset(self.get_queryset())
        queryset = queryset.filter(project__id=project_id)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def perform_create(self, serializer):
        project_id = ###  Need "project_id" here
        project = projects_models.Project.objects.get(id=data.get('project_id'))
        serializer.save(project=project)

这怎么办?

3 个答案:

答案 0 :(得分:1)

使用 self.kwargs["project_id"] project_id 方法获得 perform_create()

class ProjectCommentList(generics.ListCreateAPIView):
    ...

    def perform_create(self, serializer):
        project_id = self.kwargs["project_id"]
        project = projects_models.Project.objects.get(id=data.get('project_id'))
        serializer.save(project=project)

答案 1 :(得分:1)

在您的get方法中使用“ self”为同一类创建范围变量。

String userInput = new UiBooster().showTextInputDialog("Do you want to share file?");

答案 2 :(得分:1)

self.kwargs包含url路径中提供的所有关键字参数。因此,我们可以像访问project_id一样访问self.kwargs['project_id']。使用print(self.kwargs)之类的打印语句来了解self.kwargs的实际用途。

def perform_create(self, serializer):
    # ... your code
    project_id = self.kwargs['project_id']
    # ... your code