Django Rest Framework:同一APIView设置独立POST与GET请求URL的实现疑问
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 yourgetmethod's signature, which expects these two parameters. The{'get': 'get'}argument tells DRF that this URL should only trigger the view'sgetmethod, 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 yourpostmethod 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'spostmethod as expected. - For GET requests, send them to
/a-query/{your_param1}/{your_param2}/with the appropriate values forparam1andparam2, and it will execute your custom query logic in thegetmethod.
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

