我试图使用Django REST框架在单个基于通用类的API中实现所有CRUD。有没有办法在不更改终点的情况下并且在其中包含<int:pk>
的情况下实现此目的?
我的主要动机是在URL文件中不包含<int:pk>
,如果这样做的话,我将无法使用该URL进行创建。
api.py
from rest_framework import permissions
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.views import APIView
from django.contrib.auth import get_user_model # used custom user model
from rest_framework import mixins
from .serializers import UserSerializer
User = get_user_model()
class UserAPI(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, GenericAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'pk'
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
urls.py
from django.urls import path, include, re_path
from .api import UserAPI
urlpatterns = [
path('register/<int:pk>', UserAPI.as_view(), name='user_create'),
]
serializers.py
from rest_framework import serializers
from django.contrib.auth import get_user_model
from django.forms import ValidationError
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
write_only_fields = ('password',)
read_only_fields = ('id',)
extra_kwargs = {'last_name': {'required': True}}
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = User.objects.create(email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
)
user.set_password(validated_data['password'])
user.save()
return user
答案 0 :(得分:2)
使用Modelviewset
代替GenericAPIView
from rest_framework import viewsets
class UserAPI(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
并将您的urls.py
更改为
from django.urls import path, include, re_path
from .api import UserAPI
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'register', UserAPI)
urlpatterns = [
] + router.urls
DefaultRouter类提供CRUD操作所需的所有端点。
这是API参考表:
| API end-points | HTTP Method | Result |
|--------------------- |------------- |------------------------------------------ |
| /register | GET | List of Users |
| /register | POST | Create new User |
| /register/{user_pk} | GET | Retrieve details of particular user |
| /register/{user_pk} | PUT | Fully update particular user's info |
| /register/{user_pk} | PATCH | Partially update particular user's info |
| /register/{user_pk} | DELETE | Delete particular User's details from DB |