Django Rest框架URL参数

v09wglhw  于 2023-02-20  发布在  Go
关注(0)|答案(1)|浏览(157)

目前,我必须显示特定研讨会的所有客户,然后我使用以下URL:http://本地主机:8000/客户列表/?研讨会ID = 1
在我看来,我有以下实现:

class CustomerList(ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    filter_backends = [SearchFilter]
    search_fields = ['customer_name']
    
    def filter_queryset(self, queryset):
        workshop_id = self.request.query_params.get('workshop_id', None)
        if workshop_id is not None:
            queryset = queryset.filter(workshop_id=workshop_id)
        return queryset
    def list(self,request,*args,**kwargs):
        workshop_id = self.request.query_params.get('workshop_id', None)
        
        if not (workshop_id):
            return Response({"status": "Required field not found."},
                                        status=status.HTTP_404_NOT_FOUND)
        return super(CustomerList, self).list(request,*args,**kwargs)

URL路径如下所示:

path('customer-list/', views.CustomerList.as_view(),name='customer_list'),

但我想我的网址应该看起来像这样:http://localhost:8000/{研讨会ID}/客户列表
如何设置URL路径:
以及如何在客户视图中获取workshop_id以应用过滤器:
我已经尝试改变网址模式,但它没有工作。

iovurdzv

iovurdzv1#

要将workshop_id作为URL参数传递,只需在路径中定义它,例如:

path('<int:workshop_id>/customer-list/', views.CustomerList.as_view(),name='customer_list')

你可以从self.kwarg得到参数:

class CustomerList(ListAPIView):
    ...
    def list(self, request, *args, **kwargs):
        workshop_id = self.kwargs.get('workshop_id', None)
        ...

相关问题