get from http://127.0.0.1:8000/api/album_list_mixin
postman posts to http://127.0.0.1:8000/api/album_list_mixin
post successful, new id =35
postman get from http://127.0.0.1:8000/api/album_detail_mixin/35/
postman send put request to http://127.0.0.1:8000/api/album_detail_mixin/35/ to change artist to 'new postman'
artist is changed, put request is successful
postman send delete request to http://127.0.0.1:8000/api/album_detail_mixin/35/
delete request is successful
#music/api/mixins
from music.api.serializers import MusicSerializer
from rest_framework import mixins
from rest_framework import generics
class AlbumListMixin(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Album.objects.all()
serializer_class = MusicSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class AlbumDetailMixin(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Album.objects.all()
serializer_class = MusicSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
--------------------------------------
#music/api/urls
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from music.api import apiview, mixins
app_name = 'musicAPI'
urlpatterns = [
path('album_list', apiview.AlbumList.as_view(), name='AlbumList'),
path('album_detail/<int:pk>/', apiview.AlbumDetail.as_view(), name='AlbumDetail'),
path('album_list_mixin', mixins.AlbumListMixin.as_view(), name='AlbumListMixin'),
path('album_detail_mixin/<int:pk>/', mixins.AlbumDetailMixin.as_view(), name='AlbumDetailMixin')
]
urlpatterns = format_suffix_patterns(urlpatterns)
reference:
https://chuanshuoge2.blogspot.com/2019/05/django-35-rest-framework-apiview-get.html
No comments:
Post a Comment