Django 无法使用 pk MultiValueDictKeyError 以外的查询参数测试 API 补丁方法

Django Unable to test API patch method with query parameters other than pk MultiValueDictKeyError

我有一个 APIView 为一个实体(比如说钱)实施补丁。我可以从 axios 发送请求并且钱得到更新,但我无法使测试工作。当我通过测试用例中的 self.client.patch 发送 request.query_params 时,它们是空的。 然后它抛出 MultiValueDictKeyError('money_code') 这是代码:

class UpdateMoneyQuantity(APIView):
    def patch(self, request):
        try:
            money_code = request.query_params["money_code"]
            money_object = Money.objects.get(money_code=money_code)
            # set partial=True to update a data partially
            serializer = MoneySerializer(
                money_object, data=request.data, partial=True
            )
            if serializer.is_valid():
                serializer.save()
                return Response(data=serializer.data, status=HTTP_200_OK)
            return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)
        except Money.DoesNotExist as err:
            return Response(
                data={
                    "error": "Unable to find the desired code."
                },
                status=HTTP_400_BAD_REQUEST,
            )
        except Exception as err:
            logger.exception(
                f"Unable to perform patch on money quantity. \n Exception: {str(err)}"
            )
            return Response(data=str(err), status=HTTP_500_INTERNAL_SERVER_ERROR)

这是url:

path(
    "update-money-quantity/",
    UpdateMoneyQuantity.as_view(),
    name="update-money-quantity",
),

这是我正在尝试编写但无法使其工作的测试用例。

class MoneyUpdateTest(APITestCase):
        def test_update_quantity(self):
            """
            Ensure we can update the quantity.
            """
            obj = Money.objects.create(
                money_code="RG100TEST1",
                supplier="Test supplier",
            )
            params = {"money_code": "RG100TEST1"}
            url = reverse("update-money-quantity")
            data = {
                "saving": 110,
                "actual_saving": 105,
            }
            response = self.client.patch(url, data=data, query_params=params)
            self.assertEqual(response.status_code, HTTP_200_OK)
            self.assertEqual(
                Money.objects.get(money_code="RG100TEST1").saving, 110
            )
            self.assertEqual(
                Money.objects.get(money_code="RG100TEST1").actual_saving, 105
            )

您必须将 money_code 发送到您的视图:

更改此行

 url = reverse("update-money-quantity")

 url = f'{reverse("update-money-quantity")}?money_code={obj.money_code}'

发送money_code作为查询参数