Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django REST Frameworkに再挑戦 その4

概要

Django REST Frameworkに再挑戦 その4

参考サイト

www.django-rest-framework.org

www.codingforentrepreneurs.com

Create Serializer and Create API View

  • PostCreateSerializerを作成する。serializers.pyに追記する。
class PostCreateSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = [
            # 'id',
            'title',
            # 'slug',
            'content',
            'publish',
        ]
  • api/views.pyにCreateViewを追記する。
...
from rest_framework.generics import (
    CreateAPIView,
    DestroyAPIView,
    ListAPIView,
    UpdateAPIView,
    RetrieveAPIView,
    )

from posts.models import Post
from .serializers import (
    PostCreateSerializer,
    PostDetailSerializer,
    PostListSerializer,
    )

class PostCreateAPIView(CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostCreateSerializer
...
  • api/urls.pyに追記する。
urlpatterns = [
...
    url(r'^create/$', PostCreateAPIView.as_view(), name='create'),
...
]
  • この状態で、api/posts/createにアクセスすると、createフォームが表示される。

  • PostCreateSerializer -> PostCreateUpdateSerializer に変更する。これは、createフォームと、updateフォーム両方兼用で使えるように、わかりやすい名前に変えておくだけ。

Associate User with View Methods (Userに関連づけたView Methods)

  • PostListSerializerclassに,userフィールドを追記する。
class PostListSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = [
            'user',
            'title',
            'slug',
            'content',
            'publish',
        ]
  • model.Postで、userはdefault=1と設定されているので、現時点では全て1になっているはず。

  • userを設定するには、PostCreateAPIView(CreateAPIView)を修正する。

class PostCreateAPIView(CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostCreateUpdateSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user, title='my title')

公式サイトは以下のページを参照(perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance.とある):

Generic views - Django REST framework

  • perform_createを定義した後に、createフォームからpostすると、以下のようにuser, title共に、狙い通り登録される。
    {
        "user": 2,
        "title": "my title",
        "slug": "my-title",
        "content": "de",
        "publish": "2017-01-16"
    },
  • PostUpdateAPIViewの継承するclassをUpdateAPIView->RetrieveUpdateAPIViewに変更する。これによって、現在のテーブルの内容がプレビューできるようになる。超楽!
class PostUpdateAPIView(RetrieveUpdateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostCreateUpdateSerializer
    lookup_field = 'slug'