3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Django REST Framework] APIViewを使ったときのurls.pyの書き方

Posted at

APIViewを使ったときのurls.pyの書き方

結論

ViewSetとAPIViewだとurlの定義方法が違うので注意しましょうという話

urls.py
router = routers.SimpleRouter()
router.register(r'users', UserViewSet) # ViewSet
router.register(r'accounts', AccountViewSet) # ViewSet

urlpatterns = [
    path('forgot-password/', SampleView.as_view()), # APIView
]

urlpatterns += router.urls

過程

APIViewは任意のエンドポイントを定義したいときに使うViewクラスで例えばPOSTだと以下のように書く。

views.py
class SampleView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = SampleSerializer(data=request.data)
        serializer.is_valid(raise_exceptions=True)  
        serializer.save()
        return Response(serializer.data)

これに対してViewSetはモデルに足してCURDを全部定義してくれるViewクラスである。

views.py
class SampleModelViewSet(viewsets.ModelViewSet): 
    queryset = TestModel.objects.all()
    serializer_class = TestModelSerializer

この2つでurlsの書き方が違うというところが罠。

# 参考文献

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?