博客五部曲之三 - 博客RESTful


1777 浏览 5 years, 9 months

20 创建评论序列化函数 2

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

创建评论序列化函数 2

为CommentManager添加创建评论函数,同时在其序列化创建函数create里调用它去实现comment的创建

其中的user是暂时的,后面会实现它

comments/models.py

class CommentManager(models.Manager):
    def create_by_model_type(self, model_type, slug, content, user, parent_obj=None):
        model_qs = ContentType.objects.filter(model=model_type)
        if model_qs.exists():
            SomeModel = model_qs.first().model_class()
            obj_qs = SomeModel.objects.filter(slug=slug)
            if obj_qs.exists() and obj_qs.count() == 1:
                instance = self.model()
                instance.content = content
                instance.user = user
                instance.content_type = model_qs.first()
                instance.object_id = obj_qs.first().id
                if parent_obj:
                    instance.parent = parent_obj
                instance.save()
                return instance
        return None
from django.contrib.auth import get_user_model
User = get_user_model()

def create_comment_serializer(model_type='post', slug=None, parent_id=None):
    class CommentCreateSerializer(ModelSerializer):
        def create(self, validated_data):
            content = validated_data.get("content")
            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, user,
                    parent_obj=parent_obj,
                    )
            return comment