TypeError:SearchProduct.get() 得到意外的关键字参数“query”

问题描述 投票:0回答:1

windows 10 中,我正在使用 react-router-dom 5.2.0react-redux 7.2.5react 17.0.2axios 0.21.4WebStorm 2023.1.3 IDEPyCharm 社区版 2023.2djangorestframework==3.14.0Django==4.2.4djangorestframework-simplejwt==5.3.0.

问题:其实我不知道如何将这个

query
参数发送到Django的基类视图继承自
GenericAPIView
,如何解决这个错误?

后端

考虑-product_views.py:

class SearchProduct(GenericAPIView):

    serializer_class = ProductSerializer
    pagination_class = CustomPagination1

    def get_queryset(self, *args, **kwargs):
        # the lead id
        query = self.request.GET.get("query")

        #  this filter base on the lead id  provided
        lookup = Q(name__icontains=query) | Q(description__icontains=query) | Q(producttag__title__icontains=query)
        products = Product.objects.filter(lookup).distinct()

        return products
    def get(self, request):


        page = self.paginate_queryset(self.get_queryset())
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            result = self.get_paginated_response(serializer.data)
            data = result.data  # pagination data

        else:
            serializer = self.get_serializer(queryset, many=True)
            data = serializer.data
        payload = {
            'return_code': '0000',
            'return_message': 'Success',
            'data': data
        }
        return Response(data , status=status.HTTP_200_OK)

考虑-product_urls.py:

 path('search_product/<str:query>/' , views.SearchProduct.as_view() , name="search_product"),

前端

考虑-productAction.py:

export const productsSearchAction = (query , pageNumber) => async (dispatch , getState) => {
    try {
        dispatch({type: PRODUCTS_SEARCH_REQUEST});
        const {data} = await axios.get(`http://127.0.0.1:8000/api/v1/products/search_product/${query}/?page=${pageNumber}`);
        dispatch({type: PRODUCTS_SEARCH_SUCCESS , payload: data});
        localStorage.setItem("productsSearch" , JSON.stringify(data));
    } catch (error) {
        dispatch({ // PRODUCTS SEARCH FAILED
            type: PRODUCTS_SEARCH_FAILED,
            payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
        });
    }
}

我认为答案很简单,如果您是 Django 和 Django Rest Framework 的专家,请回复我以便解决此错误。

我的错误屏幕

reactjs django django-rest-framework axios django-views
1个回答
0
投票

您的

.get(…)
方法需要接受 URL 路径参数,在这里您最好只接受所有位置和命名参数:

class SearchProduct(GenericAPIView):
    serializer_class = ProductSerializer
    pagination_class = CustomPagination1

    def get(self, request, *args, **kwargs):
        # …

注意:在 Django 中,基于类的 API 视图 (CBV) 通常具有

…APIView
后缀,以避免与模型名称冲突。 因此,您可能会考虑将视图类重命名为
SearchProductAPIView
,而不是
SearchProduct

© www.soinside.com 2019 - 2024. All rights reserved.