class CreateCollectSerializer(serializers.Serializer): """用户收藏序列化器""" user_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='用户id') category_id = serializers.IntegerField(label='收藏类别id') resource_id = serializers.IntegerField(label='资源id') # 去除校验,增加速度 # def validate_category_id(self, category_id): # res = CollectCategory.objects.filter(id=category_id, user_id=self.context['request'].user.id).only('id') # if not res: # raise serializers.ValidationError({'code': RET.PARAMERR, 'msg': '用户不存在该分类!'}) # return category_id # # def validate(self, attr): # type = attr.get('type') # resource_id = attr.get('resource_id') # resource = Collect.TYPE_MODEL[type].objects.filter(id=resource_id).only('id').first() # if not resource: # raise serializers.ValidationError({'code': RET.PARAMERR, 'msg': '不存在该资源!'}) # return attr def create(self, attr: dict): user_id = self.context['request'].user.id resource_id = attr.get('resource_id') category_id = attr.get('category_id') model = CollectRedisModel(user_id, category_id) is_active = model.create_or_delete(resource_id) attr['is_active'] = is_active self._data = { 'success': True, 'code': RET.OK, 'data': '💕收藏成功!' if is_active else '💔取消收藏...' } return attr
class FeedbackCategorySerializer(serializers.ModelSerializer): """查看反馈类别""" author_id = serializers.HiddenField(default=CurrentUserIdDefault()) class Meta: model = FeedbackCategory exclude = ("created_time", 'update_time', 'is_active')
class CollectCategorySerializer(serializers.ModelSerializer): """收藏分类视图""" # url = serializers.HyperlinkedIdentityField( # view_name='v1:web:user_collect-detail', # lookup_field='pk' # ) user_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='用户') is_active = serializers.ReadOnlyField(label='状态') is_show = serializers.BooleanField(label='是否可见', required=False) image = serializers.URLField(label='封面图片', required=False, allow_blank=True) desc = serializers.CharField(label='描述', allow_blank=True, required=False) total = serializers.ReadOnlyField(label='文章总和') is_like = serializers.SerializerMethodField(label='资源是否在此收藏集中') created_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d', label='创建日期') # redis版本 def get_is_like(self, obj): if self.context.get('resource_id'): model = CollectRedisModel(self.context['user_id'], obj.id) return model.get_is_like(self.context['resource_id']) return False class Meta: model = CollectCategory fields = "__all__"
class CreateFocusSerializer(serializers.Serializer): """用户关注序列化器""" is_active = serializers.ReadOnlyField(label='状态') user_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='用户id') focus_id = serializers.IntegerField(label='关注用户id') created_time = serializers.DateTimeField(read_only=True, label='关注时间') def validate_focus_id(self, focus_id): if focus_id == self.context['request'].user.id: raise serializers.ValidationError({ 'code': RET.PARAMERR, 'msg': '用户不能关注自己!' }) focus_user = User.objects.filter(id=focus_id).first() if not focus_user: raise serializers.ValidationError({ "code": RET.PARAMERR, 'msg': '不存在该用户!' }) return focus_id def create(self, validated_data: dict): user_id = validated_data.get('user_id') focus_id = validated_data.get('focus_id') obj, created = Focus.raw_objects.get_or_create(focus_id=focus_id, user_id=user_id, defaults=validated_data) if not created: obj.is_active = not F('is_active') obj.save() return obj
class UpdateFeedbackSerializer(serializers.ModelSerializer): reply_author_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='回复人id') reply_time = serializers.DateTimeField(read_only=True, label='回复时间') def validate(self, attrs): attrs['reply_time'] = datetime.datetime.now() return attrs class Meta: model = Feedback fields = ('reply_author_id', 'reply', 'reply_time')
class UploadHistorySerializer(serializers.ModelSerializer): user_id = serializers.HiddenField(default=CurrentUserIdDefault()) url = serializers.URLField(label='资源链接') bucket = serializers.CharField(label='桶') file = serializers.CharField(label='资源名称') raw_file = serializers.CharField(label='资源原名') size = serializers.FloatField(label='大小') def validate_size(self, size): """文件大小,保留一位小数,以 kb 为单位""" size = size / 1024 return round(size, 1) # url = serializers.FileField(read_only=True) # file = serializers.FileField(required=True, label='文件', write_only=True) # upload_path = RangeField(iterable=os.listdir(settings.MEDIA_ROOT), # label='上传目录', # required=False, # error_messages='不存在此目录!', # write_only=True) def validate(self, attrs): # file = attrs.pop('file') # upload_path = attrs.pop('upload_path', '') # attrs['url'] = self.save_file(file, upload_path) return attrs @staticmethod def save_file(file, upload_path): """ 保存上传的文件 :param file: 文件对象 :param upload_path: 文件要保存的目录 :return: """ file.name = random_filename(file.name) file_path = os.path.join(settings.MEDIA_ROOT, upload_path, file.name) with open(file_path, 'wb') as f: for i in file.chunks(): f.write(i) return os.path.join(upload_path, file.name) class Meta: model = UploadHistoryModel exclude = ('is_active', )
class PostCategorySerializer(serializers.ModelSerializer): """帖子无限级分类""" author_id = serializers.HiddenField(default=CurrentUserIdDefault()) child = serializers.ReadOnlyField(label='全部子节点') name = serializers.CharField(validators=[ UniqueValidator(queryset=Category.objects.all(), message={ 'code': RET.PARAMERR, 'msg': '分类名称已存在!' }) ]) class Meta: model = Category fields = [ "id", "name", "parent_id", "level", "desc", 'author_id', 'child', 'parent' ]
class CreateFeedbackSerializer(serializers.ModelSerializer): """提交反馈""" author_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='创建人') category_id = serializers.IntegerField(label='类别') def validate_category_id(self, category_id): f_c = FeedbackCategory.objects.filter( id=category_id).only('id').first() if not f_c: raise serializers.ValidationError({ 'code': RET.PARAMERR, 'msg': '不存在此类别!' }) return category_id class Meta: model = Feedback exclude = ('reply', 'reply_author_id', 'is_active')
class UserPostSerializer(serializers.ModelSerializer): """帖子序列化器""" id = serializers.ReadOnlyField(label='帖子id') author_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='创建人') post_num = serializers.ReadOnlyField(label='评论数量') read_num = serializers.ReadOnlyField(label='浏览数量') like_num = serializers.ReadOnlyField(label='收藏数量') praise_num = serializers.ReadOnlyField(label='点赞数量') status = serializers.ReadOnlyField(label='帖子状态') name = serializers.CharField(validators=[ UniqueValidator(queryset=Post.objects.all(), message={ 'code': RET.PARAMERR, 'msg': '帖子名称已存在!' }) ]) category = serializers.ListField(label='帖子分类', write_only=True) content_type = RangeField(iterable=list(dict(Post.content_type_choices)), label='文章书写类型', required=True, error_messages='文章书写类型传递错误!', data_type=int) post_type = RangeField(iterable=list(dict(Post.post_type_choices)), label='文章类型', required=True, error_messages='文章类型传递错误!', data_type=int) def validate_category(self, category): if not category: raise serializers.ValidationError({ 'code': RET.PARAMERR, 'msg': '类别必须选择' }) c = category.pop() return c class Meta: model = Post exclude = ("content", "html_content")
class PostReplySerializer(serializers.ModelSerializer): """帖子内回复序列化器""" praise_num = serializers.ReadOnlyField(label='点赞数量') status = serializers.ReadOnlyField(label='状态') replier_id = serializers.ReadOnlyField(label='回复用户id') author_id = serializers.HiddenField(default=CurrentUserIdDefault(), label='创建人') post_id = serializers.IntegerField(label='回复帖子id') def validate_post_id(self, post_id): post = Post.objects.filter(id=post_id).first() if post is None: raise serializers.ValidationError({ 'code': RET.PARAMERR, 'msg': f'{post_id}回复帖子不存在!' }) if not post.not_reply: raise serializers.ValidationError({ 'code': RET.PARAMERR, 'msg': f'帖子{post.name},不允许回复!' }) return post_id def validate(self, attr): parent = attr.get('parent') if parent: attr['replier_id'] = parent.author_id return attr replier_info = serializers.SerializerMethodField(label='回复用户信息') type = serializers.SerializerMethodField(label='回复帖子/回复用户') author_info = serializers.SerializerMethodField(label='创建人信息') is_del = serializers.SerializerMethodField(label='是否可删除') child_num = serializers.SerializerMethodField(label='子评论数量') def get_author_info(self, obj): """回复创建人信息""" user = User.get_simple_user_info(obj.author_id) if user: return user def get_replier_info(self, obj): """ 返回回复人信息 :param obj: :return: """ if obj.replier_id: return User.get_simple_user_info(obj.replier_id) def get_type(self, obj): """ 获取回复的类型 :return: 1-->回复帖子 2-->回复用户 """ return 1 if not obj.parent else 2 def get_is_del(self, obj): """ 用户是否可以删除该回复, 创建人是该用户&回复并没有子回复 """ return obj.is_del(self.context['request'].user.id) def get_child_num(self, obj): """返回回复的子回复数量""" return obj.get_descendant_count() class Meta: model = PostReply exclude = ("lft", "rght")