Django Rest Framework APIClient不解析查询参数

Ami*_*irM 5 django django-testing django-rest-framework

我正在使用djangorestframework==3.3.3Django==1.9.4

我有一个测试,我想检查查询参数是否正确处理。

class TestResourceView(APITestCase):

    def test_view_process_query_params_correctly(self):
        client = APIClient()
        client.login(username='<username>', password='password')
        response = client.get('/api/v2/resource/1/users/?fields=first_name;last_name')
        self.assertEqual(response.status_code, 200)
        # .... rest of the test .... 
Run Code Online (Sandbox Code Playgroud)

在我看来,我放置print语句只是为了查看查询参数是否正确解析,但我得到空查询字典:

class Resource(APIView):
    def get(self, request):
        query_params = request.query_params
        print('Printing query params')
        print(query_params)
        # .... rest of the code ....

    def post(self, request):
        query_params = request.query_params
        print('Printing query params')
        print(query_params)
        # .... rest of the code ....
Run Code Online (Sandbox Code Playgroud)

运行测试时终端结果:

Printing query params
<QueryDict: {}>
Run Code Online (Sandbox Code Playgroud)

同时,如果我post像这样测试请求:

response = client.post('/api/v2/resource/1/users/?fields=first_name;last_name')
Run Code Online (Sandbox Code Playgroud)

我得到的参数解析错误:

Printing query params
<QueryDict: {'last_name': [''], 'fields': ['first_name']}>
Run Code Online (Sandbox Code Playgroud)

正确的使用方法是什么APIClient?或者这仍然是一个错误?因为已经有类似的问题了

cam*_*den 0

您的查询参数的格式不正确。

如果您希望结果是{'fields': ['last_name', 'first_name']},那么您的 POST url 应该是.../users/?fields=first_name&fields=last_name'您可能希望使用getlist()访问参数。