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

Django Rest Framework:同一APIView设置独立POST与GET请求URL的实现疑问

How to Set Separate URLs for POST and GET in Django REST Framework's APIView

Got it, let's walk through how to split your AQuery APIView's GET and POST methods into distinct URLs—this is straightforward in Django REST Framework!

Step 1: Update Your URL Configuration

In your project or app's urls.py, you can define separate routes for each HTTP method, explicitly mapping them to the corresponding methods in your AQuery view. This lets you use unique paths for GET and POST, and restricts each URL to only accept its intended method.

Here's what your urls.py should look like:

from django.urls import path
from .views import AQuery

urlpatterns = [
    # URL for GET requests (requires param1 and param2 path parameters)
    path('a-query/<str:param1>/<str:param2>/', AQuery.as_view({'get': 'get'}), name='a-query-retrieve'),
    # URL for POST requests (no extra path parameters needed)
    path('a-query/create/', AQuery.as_view({'post': 'post'}), name='a-query-create'),
]

What's Happening Here?

  • GET Route: The path includes <str:param1> and <str:param2> to match your get method's signature, which expects these two parameters. The {'get': 'get'} argument tells DRF that this URL should only trigger the view's get method, and reject any other HTTP methods.
  • POST Route: We use a distinct path (/a-query/create/) to avoid confusion with the GET route. The {'post': 'post'} argument restricts this URL to only accept POST requests, which aligns with your post method that doesn't require path parameters.

Testing the Setup

  • For your POST request to create an A record, send it to /a-query/create/ with your payload {'name': 'foo', 'another_field': 2}—this will hit your view's post method as expected.
  • For GET requests, send them to /a-query/{your_param1}/{your_param2}/ with the appropriate values for param1 and param2, and it will execute your custom query logic in the get method.

Optional: Split Into Separate Views (If Preferred)

If you want even clearer separation, you could split AQuery into two separate APIView classes: one for GET operations and one for POST. But the above approach keeps your existing view intact while achieving the separate URL goal.

内容的提问来源于stack exchange,提问作者OneRaynyDay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:09:04