Пример #1
0
class NotificationSerializer(serializers.ModelSerializer):
    sender = UserListSerializer(required=False)
    receiver = UserListSerializer(required=False)
    content_object = NotifiedObjectRelatedField(read_only=True)

    class Meta:
        model = Notification
        fields = [
            "id", "sender", "receiver", "content_object", "notification_type"
        ]
        read_only_fields = [
            "id",
        ]
Пример #2
0
class ArticleDetailSerializer(serializers.ModelSerializer):
    board_id = serializers.IntegerField(source='board.id')
    board_name = serializers.CharField(source='board.title')
    user = UserListSerializer()
    like_count = serializers.SerializerMethodField()
    like_yn = serializers.SerializerMethodField()
    comment_count = serializers.SerializerMethodField()
    comments = ArticleCommentSerializer(source='comment_set', many=True)

    def get_like_count(self, obj):
        return obj.like_users.count()

    def get_like_yn(self, obj):
        request = self.context.get('request', None)
        if obj.like_users.filter(id=request.user.id).exists():
            return 1
        return 0

    def get_comment_count(self, obj):
        return obj.comment_set.count()

    class Meta:
        model = Article
        fields = [
            'board_id', 'board_name', 'user', 'id', 'title', 'content',
            'created_at', 'updated_at', 'like_yn', 'like_count',
            'comment_count', 'comments', 'hit'
        ]
Пример #3
0
class ArticleSerializer(serializers.ModelSerializer):
    user = UserListSerializer(required=False)
    like_count = serializers.SerializerMethodField()
    like_yn = serializers.SerializerMethodField()
    comment_count = serializers.SerializerMethodField()
    board = BoardListSerializer(required=False)

    def get_like_yn(self, obj):
        request = self.context.get('request', None)
        if request.user.is_authenticated:
            if obj.like_users.filter(id=request.user.id).exists():
                return 1
        return 0

    def get_like_count(self, obj):
        return obj.like_users.count()

    def get_comment_count(self, obj):
        return obj.comment_set.count()

    class Meta:
        model = Article
        fields = [
            'id', 'title', 'content', 'created_at', 'updated_at', 'like_count',
            'like_yn', 'comment_count', 'user', 'hit', 'board'
        ]
Пример #4
0
class CommentCreateSerializer(serializers.ModelSerializer):
    user = UserListSerializer(required=False)
    article = ArticleCommentSerializer(required=False)

    class Meta:
        model = Comment
        fields = '__all__'
Пример #5
0
def check(request):
    if request.user.room:
        room = request.user.room
        serializer = RoomSerializer(room)
        members = room.members.all()
        res = {'members': []}
        now = datetime.now()
        for member in members:
            posture = []
            ls = []
            if member.sensing.all():
                # 오늘 통계 (방 생성 후 조건도 포함)
                today = date.today()
                cnt = Sensing.objects.filter(user=member).filter(
                    created_at__gte=datetime.combine(today, time.min)).filter(
                        created_at__gte=room.created_at).count()
                if cnt:
                    avg = Sensing.objects.filter(user=member).filter(
                        created_at__gte=datetime.combine(today, time.min)
                    ).filter(created_at__gte=room.created_at).aggregate(
                        Sum('posture_level'))['posture_level__sum'] / cnt
                    posture.append(round(avg, 2))
                else:
                    posture.append(0)
                # 방 생성 후 총 통계
                cnt = Sensing.objects.filter(user=member).filter(
                    created_at__gte=room.created_at).count()
                if cnt:
                    avg = Sensing.objects.filter(user=member).filter(
                        created_at__gte=room.created_at).aggregate(
                            Sum('posture_level'))['posture_level__sum'] / cnt
                    posture.append(round(avg, 2))
                else:
                    posture.append(0)

                # 현재 시간 기준으로 5분 전까지 30초 간격으로 자세 통계 계산
                for i in range(0, 10):
                    st = now - timedelta(seconds=i * 30)
                    ed = now - timedelta(seconds=(i + 1) * 30)
                    cnt = Sensing.objects.filter(user=member).filter(
                        created_at__lte=st, created_at__gte=ed).count()
                    if cnt:
                        avg = Sensing.objects.filter(user=member).filter(
                            created_at__lte=st,
                            created_at__gte=ed).aggregate(Sum(
                                'posture_level'))['posture_level__sum'] / cnt
                        ls.append({"time": str(st)[11:16], "score": avg})
                    else:
                        ls.append({"time": str(st)[11:16], "score": 0})
            else:
                posture = [0, 0]
            res['members'].append({
                **UserListSerializer(member).data, "posture":
                posture,
                "time":
                ls
            })
        return Response({"status": "OK", "data": {**serializer.data, **res}})
    else:
        return Response({"status": "OK", "data": None})
Пример #6
0
class ActivatedReviewSerializer(serializers.ModelSerializer):
    kindergarten = ActivatedReviewKindergartenSerializer()
    avg_score = serializers.SerializerMethodField()
    user = UserListSerializer(required=False)

    def get_avg_score(self, obj):
        return (obj.score_teacher + obj.score_director +
                obj.score_environment) / 3

    class Meta:
        model = Review
        fields = ['title', 'avg_score', 'pros', 'cons', 'kindergarten', 'user']
Пример #7
0
class ReviewSerializer(serializers.ModelSerializer):
    like_yn = serializers.SerializerMethodField()
    like_count = serializers.SerializerMethodField()
    avg_score = serializers.SerializerMethodField()
    user = UserListSerializer(required=False)

    def get_like_yn(self, obj):
        request = self.context.get('request', None)
        if obj.like_users.all():
            if request.user.id in list(obj.like_users.all().values_list(
                    'id', flat=True)):
                return 1
        return 0

    def get_avg_score(self, obj):
        return (obj.score_teacher + obj.score_director +
                obj.score_environment) / 3

    def get_like_count(self, obj):
        return obj.like_users.count()

    class Meta:
        model = Review
        exclude = ['like_users', 'kindergarten']
Пример #8
0
class ArticleCommentSerializer(serializers.ModelSerializer):
    user = UserListSerializer(required=True)

    class Meta:
        model = Comment
        fields = ['id', 'content', 'created_at', 'updated_at', 'user']
Пример #9
0
def detail_or_in_or_out(request, room_id):
    room = get_object_or_404(Room, id=room_id)
    serializer = RoomSerializer(room)
    if request.method == 'GET':
        if request.user.room == room:  # 참여 중인 방 정보만 가져올 수 있음
            members = room.members.all()
            res = {'members': []}
            now = datetime.now()
            for member in members:
                posture = []
                ls = []
                total_work_time = 0
                if member.sensing.all():
                    # 오늘 통계 (방 생성 후 조건도 포함)
                    today = date.today()
                    cnt = Sensing.objects.filter(
                        user=member).filter(created_at__gte=datetime.combine(
                            today, time.min)).filter(
                                created_at__gte=room.created_at).count()
                    if cnt:
                        avg = Sensing.objects.filter(user=member).filter(
                            created_at__gte=datetime.combine(today, time.min)
                        ).filter(created_at__gte=room.created_at).aggregate(
                            Sum('posture_level'))['posture_level__sum'] / cnt
                        posture.append(round(avg, 2))
                    else:
                        posture.append(0)
                    # 방 생성 후 총 통계
                    cnt = Sensing.objects.filter(user=member).filter(
                        created_at__gte=room.created_at).count()
                    if cnt:
                        avg = Sensing.objects.filter(user=member).filter(
                            created_at__gte=room.created_at).aggregate(
                                Sum('posture_level')
                            )['posture_level__sum'] / cnt
                        posture.append(round(avg, 2))
                    else:
                        posture.append(0)

                    # 현재 시간 기준으로 5분 전까지 30초 간격으로 자세 통계 계산
                    for i in range(0, 10):
                        st = now - timedelta(seconds=i * 30)
                        ed = now - timedelta(seconds=(i + 1) * 30)
                        cnt = Sensing.objects.filter(user=member).filter(
                            created_at__lte=st, created_at__gte=ed).count()
                        if cnt:
                            avg = Sensing.objects.filter(user=member).filter(
                                created_at__lte=st,
                                created_at__gte=ed).aggregate(
                                    Sum('posture_level')
                                )['posture_level__sum'] / cnt
                            ls.append({"time": str(st)[11:16], "score": avg})
                        else:
                            ls.append({"time": str(st)[11:16], "score": 0})

                    # 방 생성 후 총 공부 시간
                    if TimeSetting.objects.filter(user=member).filter(
                            created_at__gte=room.created_at).exists():
                        total_work_time = TimeSetting.objects.filter(
                            user=member
                        ).filter(created_at__gte=room.created_at).aggregate(
                            Sum('real_work_time'))['real_work_time__sum']
                else:
                    posture = [0, 0]
                res['members'].append({
                    **UserListSerializer(member).data, "posture":
                    posture,
                    "time":
                    ls,
                    "total_work_time":
                    total_work_time
                })
            return Response({
                "status": "OK",
                "data": {
                    **serializer.data,
                    **res
                }
            })

        else:
            return Response({
                "status": "FAIL",
                "error_msg": "참여 멤버가 아닙니다."
            },
                            status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        if not request.user.room:
            return Response({
                "status": "FAIL",
                "error_msg": "참여 중인 방이 없습니다."
            },
                            status=status.HTTP_409_CONFLICT)
        request.user.room = None
        request.user.save()
        room.member_num -= 1
        room.save()
        # 방 참여자 없을 시 방 삭제
        if room.member_num == 0:
            room.delete()
        return Response({"status": "OK"})
    else:
        if request.user.room:  # 이미 참여하고 있는 방 존재 시 참여 불가
            return Response({
                "status": "FAIL",
                "error_msg": "이미 참여중인 방이 있습니다."
            },
                            status=status.HTTP_409_CONFLICT)
        request.user.room = room
        request.user.save()
        room.member_num += 1
        room.save()
        return Response({"status": "OK"})