Пример #1
0
class PostLikedUsersSerializer(serializers.ModelSerializer):
    """게시글을 좋아요한 유저 리스트"""
    owner = SimpleProfileSerializer(read_only=True)

    class Meta:
        model = PostLike
        fields = ('id', 'owner')
Пример #2
0
class PostListSerializer(serializers.ModelSerializer):
    _photos = PhotoSerializer(many=True, read_only=True, source='photos')
    like_id = serializers.SerializerMethodField(read_only=True)
    owner = SimpleProfileSerializer(read_only=True)
    tags = TagListSerializerField()

    comments_count = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'content', 'owner', '_photos', 'comments_count',
                  'likes_count', 'like_id', 'tags')
        read_only_fields = ('owner', 'likes_count', 'comments_count')

    def get_comments_count(self, obj):
        com_count_key = f'{obj.id}comments_count'
        count = cache.get(com_count_key)
        if count is None:
            count = obj.comments_count
            cache.set(com_count_key, count, 60)
        return count

    def get_likes_count(self, obj):
        like_count_key = f'{obj.id}likes_count'
        count = cache.get(like_count_key)
        if count is None:
            count = obj.likes_count
            cache.set(like_count_key, count, 60)
        return count

    def get_like_id(self, obj):
        like_id_dict = getattr(self.context['view'], 'like_id_dict', {})
        like_id = like_id_dict.get(obj.id)
        return like_id
Пример #3
0
class LikedPostSerializer(serializers.ModelSerializer):
    owner = SimpleProfileSerializer()
    _photos = PhotoSerializer(many=True, read_only=True, source='photos')

    class Meta:
        model = Post
        fields = ('id', 'content', 'owner', '_photos')
        read_only_fields = ('owner', 'likes_count')
Пример #4
0
class StorySerializer(serializers.ModelSerializer):
    _duration = serializers.IntegerField(read_only=True,
                                         source='duration.seconds')
    read_users_count = serializers.IntegerField(
        read_only=True, source='story_checks.count')  # 읽은 유저 수
    owner = SimpleProfileSerializer(read_only=True)

    class Meta:
        model = Story
        fields = ('id', 'owner', 'content', 'img', 'duration', '_duration',
                  'created', 'read_users_count')
        extra_kwargs = {'duration': {'write_only': True}}
Пример #5
0
class StoryListSerializer(serializers.ModelSerializer):
    _duration = serializers.IntegerField(source='duration.seconds')
    watched = serializers.SerializerMethodField()
    owner = SimpleProfileSerializer()

    class Meta:
        model = Story
        fields = ('id', 'content', 'img', '_duration', 'watched', 'owner',
                  'created')

    def get_watched(self, obj):
        """이미 본 스토리인지: id 가 있으면 True"""
        story_check_dict = getattr(self.context['view'], 'story_check_dict',
                                   {})
        return story_check_dict.get(obj.id)
Пример #6
0
class FollowSerializer(serializers.ModelSerializer):
    """팔로우 시리얼라이저"""

    user = SimpleProfileSerializer(source='to_user', required=False)

    class Meta:
        model = Follow
        fields = ('id', 'user')

    def validate(self, attrs):
        # user_pk lookup 검증
        to_user_pk = self.context['view'].kwargs.get('user_pk')
        if not to_user_pk or not User.objects.filter(id=to_user_pk).exists():
            raise NotFound('User is not valid')

        # UniqueTogether 검증
        if Follow.objects.filter(owner=self.context['request'].user, to_user=to_user_pk).exists():
            raise serializers.ValidationError('The fields `owner`, `to_user` must make a unique set.',
                                              code='unique')
        return attrs
Пример #7
0
class PostSerializer(TaggitSerializer, serializers.ModelSerializer):
    photos = ListField(child=ImageField(), write_only=True)
    _photos = PhotoSerializer(many=True, read_only=True, source='photos')
    owner = SimpleProfileSerializer(read_only=True)
    tags = TagListSerializerField(required=False)

    class Meta:
        model = Post
        fields = ('id', 'content', 'owner', 'photos', '_photos', 'tags')
        read_only_fields = ('owner', )

    def create(self, validated_data):
        """Post를 만든 후 이미지들로 Photo들 생성"""
        photos = validated_data.pop('photos')
        post = Post.objects.create(**validated_data)
        photo_bulk_list = []
        for image_data in photos:
            photo = Photo(post=post, img=image_data)
            photo_bulk_list.append(photo)
        Photo.objects.bulk_create(photo_bulk_list)
        return post
Пример #8
0
class LikeSerializer(serializers.ModelSerializer):
    """게시글 좋아요 시리얼라이저"""
    owner = SimpleProfileSerializer(read_only=True)

    class Meta:
        model = PostLike
        fields = ('id', 'post_id', 'owner_id', 'owner')

    def validate(self, attrs):
        # post_pk lookup 검증
        post_pk = self.context['view'].kwargs.get('post_pk')
        if not post_pk or not Post.objects.filter(id=post_pk).exists():
            raise serializers.ValidationError('Post is not valid')

        # UniqueTogether 검증
        if PostLike.objects.filter(owner=self.context['request'].user,
                                   post=post_pk).exists():
            raise serializers.ValidationError(
                'The fields `user`, `post` must make a unique set.',
                code='unique')
        return attrs