首页 > 代码库 > [Django] ModelViewSet from rest_framework and Router

[Django] ModelViewSet from rest_framework and Router

To build rest api easily, we can use ModelViewSet from rest_framework.

It provides GET, POST, DELETE, PUT methods.

from rest_framework.viewsets import ModelViewSetfrom .serializers import ListSerializer, CardSerializerfrom .models import List, Cardclass ListViewSet(ModelViewSet):    queryset = List.objects.all()    serializer_class = ListSerializerclass CardViewSet(ModelViewSet):    queryset = Card.objects.all()    serializer_class = CardSerializer

 

To render those model view set, you can use router provided by rest_framework.

By default, it end with slash!

from .api import ListViewSet, CardViewSetfrom rest_framework.routers import DefaultRouterrouter = DefaultRouter()router.register(rlists, ListViewSet)router.register(rcards, CardViewSet)urlpatterns = router.urls

 

[Django] ModelViewSet from rest_framework and Router