新手求教:如何编辑Django REST Swagger的实现笔记与参数描述
Hey there! Let's break down how to customize both the Implementation Notes and parameter descriptions for your CrashViewSet—I'll walk you through each part step by step, using your existing code as a starting point.
a) Editing Implementation Notes
Implementation Notes (or general viewset context) come directly from your viewset's docstring, and you can expand them to include details about how the endpoint works, dependencies, or important implementation specifics. Here's how to enhance yours:
1. Expand the Viewset's Main Docstring
You already have basic descriptions for the retrieve and list actions, but you can add a top-level section for implementation notes and flesh out descriptions for all supported actions (like create, update, etc.).
Modified example docstring:
class CrashViewSet(viewsets.ModelViewSet): """ API endpoint for managing crash incident records. **Implementation Notes** - Uses three filter backends: `SearchFilter` (for text searches), `DjangoFilterBackend` (for field-specific filters), and `OrderingFilter` (for sorting results). - All model fields are allowed for ordering via `ordering_fields = '__all__'`—prefix a field name with `-` to sort descending. - Search supports partial matches across text-heavy fields like `crash_id`, `crash_hr_short_desc`, and `urb_area_short_nm`. retrieve: Fetch a single Crash instance by its unique ID, including all associated metadata. list: Retrieve a paginated list of all Crash records. Supports filtering, searching, and ordering via query parameters. create: Create a new Crash record. Requires all mandatory fields defined in `CrashSerializer`. update: Fully overwrite an existing Crash record—must provide values for all fields. partial_update: Modify specific fields of an existing Crash record; only provided fields will be updated. destroy: Permanently delete a Crash record from the database. """ # Rest of your existing code...
Swagger will use the top-level text as the Implementation Notes for the entire viewset, and each action's description will appear under its respective endpoint in the UI.
2. Granular Control with swagger_auto_schema
If you need to override descriptions for individual actions (e.g., add more context to retrieve), use the swagger_auto_schema decorator (from drf_yasg, the modern replacement for Django REST Swagger):
from drf_yasg.utils import swagger_auto_schema class CrashViewSet(viewsets.ModelViewSet): # ... your existing code ... @swagger_auto_schema( operation_summary="Get a single crash record", operation_description="Retrieve detailed metadata for a specific crash, including location, conditions, and contributing factors." ) def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs)
b) Editing Parameter Descriptions
Parameters in your viewset come from three sources: filter fields, search/ordering parameters, and serializer fields for create/update actions. Here's how to add clear descriptions to each:
1. Filter, Search, and Ordering Parameters
Instead of using filter_fields directly, define a custom FilterSet to add descriptions to each filter parameter. This works for all filter-backed query parameters.
Example custom filter class:
from django_filters import rest_framework as filters class CrashFilter(filters.FilterSet): ser_no = filters.NumberFilter(help_text="Filter crashes by their unique serial number") cnty_id = filters.NumberFilter(help_text="Filter crashes by the ID of the county where the incident occurred") alchl_invlv_flg = filters.BooleanFilter(help_text="Filter crashes where alcohol was involved (use `true` or `false`)") crash_yr_no = filters.NumberFilter(help_text="Filter crashes by the year they occurred (e.g., 2023)") # Add all your other filter fields here with corresponding help text class Meta: model = Crash fields = ['ser_no', 'cnty_id', 'alchl_invlv_flg', 'crash_yr_no', ...] # Match your original filter_fields # Update your viewset to use this filter class class CrashViewSet(viewsets.ModelViewSet): # ... your existing code ... filter_backends = (SearchFilter, DjangoFilterBackend, OrderingFilter,) filterset_class = CrashFilter # Replace filter_fields with this line # ... rest of your code ...
The help_text will automatically show up as the parameter description in Swagger.
For search and ordering parameters, customize their descriptions with swagger_auto_schema on the list action:
from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema class CrashViewSet(viewsets.ModelViewSet): # ... your existing code ... @swagger_auto_schema( manual_parameters=[ openapi.Parameter( 'search', openapi.IN_QUERY, description="Search across fields: crash_id, crash_hr_short_desc, urb_area_short_nm, and more. Use partial text matches.", type=openapi.TYPE_STRING ), openapi.Parameter( 'ordering', openapi.IN_QUERY, description="Sort results by any field. Prefix with `-` for descending order (e.g., `?ordering=-crash_yr_no`).", type=openapi.TYPE_STRING ) ] ) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs)
2. Serializer Field Descriptions
For request body parameters (used in create, update, and partial_update), add help_text to your CrashSerializer fields. These will appear in Swagger's request body schema:
from rest_framework import serializers from .models import Crash class CrashSerializer(serializers.ModelSerializer): crash_id = serializers.CharField(help_text="Unique alphanumeric identifier for the crash") crash_hr_short_desc = serializers.CharField(help_text="Short description of the crash's timing context (e.g., 'Rush Hour')") urb_area_short_nm = serializers.CharField(help_text="Short name of the urban area where the crash occurred") # Add help_text to all fields in the serializer class Meta: model = Crash fields = '__all__'
Quick Final Tips
- If you haven't already, install
drf_yasg(it's the maintained, feature-rich alternative to the original Django REST Swagger package) for better control over your docs. - After making changes, restart your server and refresh the Swagger UI to see updates—sometimes cached docs can stick around!
内容的提问来源于stack exchange,提问作者user3588841

