寻求Django 2.0多模型基础CRUD接口自动生成方案
Got it, this is exactly where Django REST Framework (DRF) shines—you can skip writing repetitive view code for every model and auto-generate all those basic CRUD endpoints in minutes. Here's a step-by-step guide tailored to your Dog model example, which you can reuse for any other model in your project:
1. Set Up Django REST Framework
First, install DRF (it’s fully compatible with Django 2.0—aim for version 3.8 or higher):
pip install djangorestframework
Add it to your INSTALLED_APPS in settings.py:
INSTALLED_APPS = [ # ... your existing apps 'rest_framework', ]
2. Create a Model Serializer
Serializers handle converting your model data to JSON (and vice versa) automatically. Create a serializers.py file in your app:
# your_app/serializers.py from rest_framework import serializers from .models import Dog class DogSerializer(serializers.ModelSerializer): class Meta: model = Dog fields = '__all__' # Use this to include all model fields, or list specific ones like ['id', 'name', 'breed']
3. Use a ModelViewSet for CRUD Logic
DRF’s ModelViewSet comes pre-packaged with all the CRUD actions you need: list (get all), retrieve (get by ID), create (post new), update (put full update), and destroy (delete). No need to write separate views for each action!
Add this to your views.py:
# your_app/views.py from rest_framework import viewsets from .models import Dog from .serializers import DogSerializer class DogViewSet(viewsets.ModelViewSet): queryset = Dog.objects.all() serializer_class = DogSerializer
4. Auto-Register Endpoints with a Router
Instead of manually defining each URL pattern, use DRF’s DefaultRouter to auto-map your viewset to the correct endpoints:
# your_project/urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from your_app.views import DogViewSet # Initialize the router and register your viewset router = DefaultRouter() router.register(r'dogs', DogViewSet) urlpatterns = [ # Include the auto-generated API URLs path('api/', include(router.urls)), # ... your other project URLs ]
What You Get Automatically
Once set up, you’ll have these ready-to-use endpoints:
GET /api/dogs/– Fetch all dogsGET /api/dogs/<id>/– Fetch a single dog by IDPOST /api/dogs/– Create a new dog (send JSON data matching your serializer fields)PUT /api/dogs/<id>/– Full update of a dog’s informationPATCH /api/dogs/<id>/– Partial update (bonus! DRF includes this by default)DELETE /api/dogs/<id>/– Delete a dog (another bonus endpoint)
Scale to Other Models
Want to add CRUD for a Cat model later? Just repeat these steps:
- Make a
CatSerializer - Create a
CatViewSetpointing to theCatmodel and serializer - Register it with the router:
router.register(r'cats', CatViewSet)
No more redundant code—each new model takes just a few lines to set up.
Customize When Needed
If you need to tweak any behavior (e.g., filter the list of dogs to only show those owned by the current user), just override the relevant method in your viewset:
def get_queryset(self): # Example: Restrict results to the logged-in user's dogs return Dog.objects.filter(owner=self.request.user)
内容的提问来源于stack exchange,提问作者Dries De Rydt

