使用 Django REST Framework 實作 model 的 CRUD

一開始我想要這樣寫:

class MonitorList(generics.ListCreateAPIView, mixins.RetrieveModelMixin, mixins.UpdateModelMixin):
queryset = Monitor.objects.all()
serializer_class = MonitorSerializer

urls.py:

urlpatterns = [
url(r'^monitors/$', views.MonitorList.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

後來發現不行,Retrieve 和 Update 必須使用自己獨立的 route 和 view, 必須和 ListView 分開,所以必須要這樣寫:

class MonitorList(generics.ListCreateAPIView):
queryset = Monitor.objects.all()
serializer_class = MonitorSerializer

class MonitorDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Monitor.objects.all()
serializer_class = MonitorSerializer

urls.py:

urlpatterns = [
url(r'^monitors/$', views.MonitorList.as_view()),
url(r'^monitors/(?P.+)/$', views.MonitorDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)