You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在另一个视图中调用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 given
  • res = 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_field attribute on the view correctly
  • res = 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:55:16