博客五部曲之三 - 博客RESTful


1331 浏览 5 years, 2 months

10 关联用户到视图方法

版权声明: 转载请注明出处 http://www.codingsoho.com/

关联用户到视图方法

我们在前面视图的操作中并没有涉及到用户相关的操作,但是post是包含user字段的,本节我们将在创建时将用户关联到post。

当前创建的post里,user总是为1,因为我们在model里这个字段的默认值就是1.

给PostCreateAPIView添加函数perform_create

class PostCreateAPIView(CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostCreateUpdateSerializer
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

除了这个字段,我们也可以同时更新其他字段,比如serializer.save(user=self.request.user, title=”title”)来更新title

用新的用户(user id = 2)登陆,创建一个新的post “new post 4”,新生成的post如下,可以看到user为2.

同样,我们可以在PostUpdateAPIView修改user

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

前面一节提到过,如果通过UpdateView更新post,表单一开始为空,我们无法直接获取当前post的内容。

RetrieveUpdateAPIView

RESTful提供了另外一个接口RetrieveUpdateAPIView,我们用它来代替RetrieveAPIView

访问http://127.0.0.1:8000/api/posts/new-post-3/edit来更新post,初始GET访问并不会报错,Allow的方式里包含了 GET和PUT,同时下面的form里初始显示了当前post的内容,这对我们修改post来说就很方便了。

PUT提交这个post,更新后的post的user变成了2.

    {
        "title": "new post 3",
        "slug": "new-post-3",
        "publish": "2018-07-07",
        "user": 2
    },

其实,在perform_update函数中,我们还可以做一些其他的操作。比如发送邮件等等。