3
4

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 5 years have passed since last update.

Django REST frameworkチュートリアル その4.2

Posted at

Associating Snippets with Users

前回の記事「Django REST frameworkチュートリアル その4.1」の続きです。
チュートリアルその4の記事で以下のTODOがありました。

スニペットを登録するときに自動でリクエストを送った人がownerとなるように登録したいです。

この機能を実装してみましょう。

views.py

この実装はかなり簡単です。SnippetListクラスのperform_create()メソッドをオーバーライドするだけです。

snippets/views.py
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from snippets.permissions import IsOwnerOrReadOnly
from django.contrib.auth.models import User
from rest_framework import generics, permissions


class SnippetList(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [IsOwnerOrReadOnly]
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer


class UserList(generics.ListCreateAPIView):
    permission_classes = [permissions.AllowAny]
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetails(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [IsOwnerOrReadOnly]
    queryset = User.objects.all()
    serializer_class = UserSerializer

公式ドキュメントを参照すると、

perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance.

とあります。perform_createCreateModelMixinから呼び出されて、新しいオブジェクトインスタンスを保存するときに呼び出されるメソッドのようですね。

テスト

スニペットを新規作成するリクエストを送ってみましょう。

curl -X POST -H 'Content-Type:application/json' -H 'Authorization: Bearer <your access token>' -d '{"title":"hoge","code":"fuga"}' http://localhost:8000/snippets/

ownerが自動で登録されるのが確認できたでしょうか。

以上でオーナーの自動登録は完了です。

3
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?