postman get last 5 albums from http://127.0.0.1:8000/api/albums_last5/
postman get all albums from http://127.0.0.1:8000/api/albums_all/
#powershell
pip install djangorestframework
------------------------------
#settings
INSTALLED_APPS = [
...
'rest_framework',
]
---------------------------------
#music/api/serializers
from rest_framework import serializers
from music.models import Album
class MusicSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ('id', 'artist', 'album_title', 'genre', 'album_logo', 'date_posted', 'author')
---------------------------------
#music/api/viewsets
from music.models import Album
from .serializers import MusicSerializer
from rest_framework import viewsets
class AlbumAllViewSet(viewsets.ModelViewSet):
queryset = Album.objects.all()
serializer_class = MusicSerializer
http_method_names = ['get']
class AlbumLast5ViewSet(viewsets.ModelViewSet):
queryset = Album.objects.all().order_by('-date_posted')[:5]
serializer_class = MusicSerializer
http_method_names = ['get']
-------------------------------------
#project1/router
from music.api.viewsets import AlbumLast5ViewSet, AlbumAllViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register('albums_all', AlbumAllViewSet)
router.register('albums_last5', AlbumLast5ViewSet)
----------------------------
#project1/urls
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from .router import router
urlpatterns = [
path('admin/', admin.site.urls),
path('music/', include('music.urls')),
path('', include('django.contrib.auth.urls')),
path('api/', include(router.urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
reference:
http://chuanshuoge2.blogspot.com/2019/05/django-34-restful-api.html
No comments:
Post a Comment