博客五部曲之三 - 博客RESTful
1477 浏览 5 years, 9 months
20 创建评论序列化函数 1
版权声明: 转载请注明出处 http://www.codingsoho.com/创建评论序列化函数 1
本节我们会讨论怎么去创建一个评论序列化类,它通过一个函数去创建。
函数参数里,slug跟object对象直接关联,我们用它来代替id去访问对象。
为什么要用函数去创建一个类?参数不是从kwargs
传进去的,而是从函数传进去的
comments.api.serializer.py
from django.contrib.contenttypes.models import ContentType
from rest_framework.serializers import (
ValidationError
)
def create_comment_serializer(model_type='post', slug=None, parent_id=None):
class CommentCreateSerializer(ModelSerializer):
class Meta:
model = Comment
fields = [
'id',
'parent',
'content',
'timestamp',
]
def __init__(self, *args, **kwargs):
self.model_type = model_type
self.slug = slug
self.parent_obj = None
if parent_id:
parent_qs = Comment.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() ==1:
self.parent_obj = parent_qs.first()
return super(CommentCreateSerializer, self).__init__(*args, **kwargs)
def validate(self, data):
model_type = self.model_type
model_qs = ContentType.objects.filter(model=model_type)
if not model_qs.exists() or model_qs.count() != 1:
raise ValidationError("This is not a valid content type")
SomeModel = model_qs.first().model_class()
obj_qs = SomeModel.objects.filter(slug=self.slug)
if not obj_qs.exists() or obj_qs.count() != 1:
raise ValidationError("This is not a slug for this content type")
return data
return CommentCreateSerializer