I was trying to implement all of CRUD in a single Generic class based API using Django REST Framework. Is there a way I can do this without changing the end point and including <int:pk>
in it?
My main motive for not including <int:pk>
in the urls file is that I will not be able to use this url for create if I did that.
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
Use Modelviewset
instead of GenericAPIView
from rest_framework import viewsets
class UserAPI(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
and change your urls.py
to
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
The DefaultRouter class provides all end-point that are required for CRUD operations.
Here is the API reference table:
| 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 |
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.