博客五部曲之三 - 博客RESTful
1463 浏览 5 years, 9 months
21 创建评论序列化函数 3
版权声明: 转载请注明出处 http://www.codingsoho.com/创建评论序列化函数 3
时间创建API视图,跟前面直接指定serializer_class
不同,本节用get_serializer_class
函数来冬天获取序列化类,另一种方式是在序列化类里调用perform_create函数 (待确认)
comments/api/views.py
class CommentCreateAPIView(CreateAPIView):
queryset = Comment.objects.all()
#serializer_class = PostCreateUpdateSerializer
permission_classes = [IsAuthenticated]
def get_serializer_class(self):
model_type = self.request.GET.get("type")
slug = self.request.GET.get("slug")
parent_id = self.request.GET.get("parent_id", None)
return create_comment_serializer(
model_type=model_type,
slug=slug,
parent_id=parent_id,
user=self.request.user
)
添加URL
urlpatterns = [
url(r'^create/$', CommentCreateAPIView.as_view(), name='create'),
]
修改create_comment_serializer函数,将用户信息传递进去
def create_comment_serializer(model_type='post', slug=None, parent_id=None, user=None):
class CommentCreateSerializer(ModelSerializer):
def create(self, validated_data):
content = validated_data.get("content")
if user:
main_user = user
else:
main_user = User.objects.all().first()
model_type = self.model_type
slug = self.slug
parent_obj = self.parent_obj
comment = Comment.objects.create_by_model_type(
model_type, slug, content, main_user,
parent_obj=parent_obj,
)
return comment
return CommentCreateSerializer
使用api创建评论 http://127.0.0.1:8000/api/comments/create/
有的时候会报下面错误,因为代码里设定了permission_classes = [IsAuthenticated],所以记得登陆授权一下
Comment Create Api
GET /api/comments/create/
HTTP 403 Forbidden
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "Authentication credentials were not provided."
}
另外,由于创建时我们要获取type和slug信息,所以需要通过GET传递进去,否则报错
http://127.0.0.1:8000/api/comments/create/?type=post&slug=test
再次执行
POST /api/comments/create/?type=post&slug=test
HTTP 201 Created
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"id": 51,
"parent": null,
"content": "this is comment",
"timestamp": "2018-07-18T13:50:18.078000Z"
}
查看 http://127.0.0.1:8000/test,新的comments已生成。
如果我们想恢复id=51的comments,可以用http://127.0.0.1:8000/api/comments/create/?type=post&slug=test&parent_id=51,添加新的参数 这样http://127.0.0.1:8000/comments/51下面就可以看到新的嵌套评论了
因为可以通过GET parent_id获取参数,我们可以把parent从Serializer里面去掉先