英文:
Django Rest Framework URL parameters
问题
目前我需要显示特定工作坊的所有客户,然后我正在使用以下URL:http://localhost:8000/customer-list/?workshop_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'),
但我想要我的URL看起来像这样:http://localhost:8000/{workshop_id}/customer-list
如何设置我的URL路径:
以及如何在客户视图中获取workshop_id以应用过滤器:
我尝试更改URL模式,但没有成功。
英文:
Currently i have to display all customers for a specific workshop then I am using following url:
http://localhost:8000/customer-list/?workshop_id=1
and in my view I have following implementation:
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 looks like this:
path('customer-list/', views.CustomerList.as_view(),name='customer_list'),
But I want my url should look like this:
http://localhost:8000/{workshop_id}/customer-list
How can I set my URL path:
and how can I get workshop_id in customer view to apply filters:
I have tried to change url pattern but it did not work.
答案1
得分: 0
只需在路径中定义workshop_id
作为URL参数,例如:
path('<int:workshop_id>/customer-list/', views.CustomerList.as_view(), name='customer_list')
然后,您可以从self.kwargs
中获取参数:
class CustomerList(ListAPIView):
...
def list(self, request, *args, **kwargs):
workshop_id = self.kwargs.get('workshop_id', None)
...
英文:
To pass workshop_id
as an URL parameter just define it in the path, for example:
path('<int:workshop_id>/customer-list/', views.CustomerList.as_view(),name='customer_list')
And you can get the parameter from self.kwarg
:
class CustomerList(ListAPIView):
...
def list(self, request, *args, **kwargs):
workshop_id = self.kwargs.get('workshop_id', None)
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论