使用 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)

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s