如何在另一个视图中调用DjangoRestFramework的DetailAPIView?
问题背景与遇到的问题
我有一个DRF的DetailAPIView(PlaceDetailAPIView),外部通过浏览器、curl等访问http://localhost:8000/api/place/6873947/可正常返回复杂序列化JSON响应,对应的URL配置为:
path('place/<int:pk>/', views.PlaceDetailAPIView.as_view(), name='place-detail'),
需要在另一个函数视图中调用该APIView,尝试了多种方法均失败:
尝试1:使用rest_framework.test.APIClient
from rest_framework.test import APIClient from django.urls import reverse client = APIClient() url = '/api/place/6873947/' res = client.get(url)
结果:返回空响应。
尝试2:使用django.test.Client
from django.test import Client c=Client()
尝试两种调用方式:
res = c.get('/api/place?pk=6873947')res = c.get('/api/place/', {'pk': 6873947})
结果:均报错as_view() takes 1 positional argument but 2 were given。
尝试3:直接调用视图类
from api.views import PlaceDetailAPIView pid = 6873947 from django.test import Client from django.http import HttpRequest from places.models import Place request = HttpRequest() request.method='GET' request.GET = {"pk": pid}
尝试三种调用方式:
res = PlaceDetailAPIView.as_view({"pk": pid}):报错as_view() takes 1 positional argument but 2 were givenres = PlaceDetailAPIView.as_view()(request=request):报错Expected view PlaceDetailAPIView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the.lookup_fieldattribute on the view correctlyres = PlaceDetailAPIView.as_view()(request=request._request):报错HttpRequest' object has no attribute '_request
解决方案
使用django.test.Client直接调用符合URL配置的路径即可(虽然调用的是DRF APIView,但此方法可行):
from django.test import Client client = Client() result = client.get('/api/place/6873947') print(result.json())
注:核心问题是之前的请求路径不符合URL配置规则,正确路径需匹配
place/<int:pk>/的格式,而非通过查询参数传递pk。
内容的提问来源于stack exchange,提问作者kgeo
相关产品推荐
相关产品推荐

