class TrackFavoriteSerializer(serializers.ModelSerializer): track = TrackListSerializer() user = UserSerializer() class Meta: model = TrackFavorite fields = ['id', 'track', 'user']
class ArtistFavoriteSerializer(serializers.ModelSerializer): artist = ArtistSerializer() user = UserSerializer() class Meta: model = ArtistFavorite fields = ['id', 'artist', 'user']
class AlbumFavoriteSerializer(serializers.ModelSerializer): album = AlbumSerializer() user = UserSerializer() class Meta: model = AlbumFavorite fields = ['id', 'album', 'user']
def get(self, request, pk, format=None): user = User.objects.get(id=pk) profile = user.profile #all related subjects to a user subjects = profile.subjects.all() user_serializer = UserSerializer(user) user_data = user_serializer.data subject_list = [] #list of subjects for a given user quiz_list = [] #list of quizes for a given user #add all relevant subjects to a list for sub in subjects: subject_serializer = SubjectInfoSerializer(sub) subject_list.append(subject_serializer.data) #all quizes related to the subject quizes = Quiz.objects.filter(subject=sub.id) #add all relevant quizes to a list for quiz in quizes: quiz_serializer = QuizSerializer(quiz) quiz_list.append(quiz_serializer.data) content = {'subjects': subject_list} user_data.update(content) content = {'quizes': quiz_list} user_data.update(content) return Response(user_data)
class ReportSerializer(serializers.HyperlinkedModelSerializer): """SQR Report serializer""" impressions = serializers.FloatField(default=0.0, source='impressions__sum', required=False) cost = serializers.FloatField(default=0.0, source='cost__sum', required=False) clicks = serializers.FloatField(default=0.0, source='clicks__sum', required=False) conversions = serializers.FloatField(default=0.0, source='conversions__sum', required=False) cpc = serializers.FloatField(default=0.0, required=False) cpa = serializers.FloatField(default=0.0, required=False) ctr = serializers.FloatField(default=0.0, required=False) index = serializers.FloatField(default=0.0, source='i', required=False) author = UserSerializer(required=False) def update(self, instance, validated_data): super().update(instance, validated_data) instance.author = self.context['request'].user instance.save() return instance class Meta: model = Report fields = ('id', 'term', 'impressions', 'clicks', 'cost', 'conversions', 'status', 'cpc', 'cpa', 'ctr', 'index', 'modified', 'author', 'source') read_only_fields = ('modified', 'auth')
class ArticleDetailsSerializer(serializers.ModelSerializer): """Article serializer.""" author = UserSerializer(read_only=True) class Meta: model = Article fields = ['id', 'author', 'title', 'article', 'tag']
def my_jwt_response_handler(token, user=None, request=None): return { 'token': token, 'user': UserSerializer(user, context={ 'request': request }).data }
class ArticleSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url') author = UserSerializer() category = CategorySerializer() comments_count = serializers.IntegerField() like_status = serializers.SerializerMethodField( method_name='get_like_status') class Meta: model = Article fields = ('id', 'title', 'url', 'author', 'category', 'created', 'updated', 'comments_count', 'image', 'likes', 'dislikes', 'like_status', 'content') read_only_fields = ('author', 'comments_count', 'url') def get_like_status(self, obj): user = self.context['request'].user if not user.is_authenticated: return LikeIconStatus.EMPTY like_obj = obj.votes.filter(user=user).first() print(like_obj) if like_obj: print(like_obj.vote) return LikeIconStatus.LIKED if like_obj.vote == LikeStatus.LIKE else LikeIconStatus.DISLIKED return LikeIconStatus.EMPTY
class CommentDetailsSerializer(serializers.ModelSerializer): """Comment Details serializer.""" article = ArticleSerializer(read_only=True) created_by = UserSerializer(read_only=True) class Meta: model = Comment fields = ['id', 'article', 'created_by', 'edited', 'comment'] read_only_fields = ('article', 'edited')
class QuestionAnswerSerializer(serializers.ModelSerializer): answer = serializers.SerializerMethodField() user = UserSerializer() class Meta: model = Question fields = ('id','user', 'title','answer',) def get_answer(self, obj): answer = Answer.objects.filter(question_id=obj.id) return AnswerSerializer(answer, many=True).data
def notify_watchers(sender, instance=Activity(), **kwargs): watchers = list(instance.ticket.watchers.all()) + \ list(instance.project.watchers.all()) watchers.append(instance.ticket.reporter) if instance.ticket.assignee is not None: watchers.append(instance.ticket.assignee) for watcher in watchers: send_notification.delay( UserSerializer(watcher).data, ActivitySerializer(instance).data)
class ActivitySerializer(serializers.ModelSerializer): """Serialize an activity into JSON""" actioning_user = UserSerializer() project = ProjectSerializer() ticket = TicketSerializer() class Meta: model = Activity fields = ('id', 'actioning_user', 'type', 'ticket', 'project', 'timestamp')
class TaskSerializer(serializers.ModelSerializer): user = UserSerializer() assignee = UserSerializer() watchers = UserSerializer(many=True, read_only=True) comments = CommentSerializer(many=True, read_only=True) client = serializers.SerializerMethodField() def get_client(self, obj): if obj.client: return { 'id': obj.client.id, 'name': obj.client.name, } return {} class Meta: model = Task fields = [ 'user', 'name', 'body', 'client', 'is_done', 'due_date', 'id', 'assignee', 'watchers', 'is_recurring', 'every', 'comments' ]
def retrieve(self, request, pk=None): object = self.get_object(pk) vignette_display = self.request.query_params.get( 'vignette_display', None) if vignette_display and vignette_display is not None: serializer = UserVignetteSerializer(object, context={'request': request}) else: serializer = UserSerializer(object, context={'request': request}) return Response(serializer.data)
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # Successful authentication. Save token serializer.save() # Prepare response serializer response_serializer = UserSerializer(serializer.context.get('user')) response = Response(response_serializer.data) # Add token to header response['x-authtoken'] = serializer.instance.token return response
class TrainingSessionSerializer(serializers.ModelSerializer): users_count = serializers.SerializerMethodField() users = UserSerializer(many=True, read_only=True) trainer = TrainerSerializer() workouts = WorkoutSerializer(many=True, read_only=True) @staticmethod def get_users_count(instance): return instance.users.all().count() class Meta: model = TrainingSession fields = ("pk", "name", "description", "start_date", "end_date", "trainer", "users", "back_ground_image", "users_count", "workouts")
def post(self, request, format=None): data = request.data user = authenticate(username=data['username'], password=data['password']) if user is not None: login(request, user) user = User.objects.get(username=data['username']) response = UserSerializer(user).data user_id = response['id'] if Teacher.objects.filter(user_id=user_id): response['employee'] = 'teacher' elif Student.objects.filter(user_id=user_id): response['employee'] = 'student' return JsonResponse(response) else: return JsonResponse({"login": False}, status=200)
class ReplyDetailsSerializer(serializers.ModelSerializer): """Comment Details serializer.""" comment = CommentSerializer(read_only=True) created_by = UserSerializer(read_only=True) class Meta: model = Reply fields = [ 'id', 'reply', 'comment', 'created_by', 'created_at', 'edited' ] extra_kwargs = { 'edited': { 'read_only': True }, }
class ContentDisplaySerializer(serializers.ModelSerializer): owner = UserSerializer() is_ownerz = serializers.SerializerMethodField() # commments_count = serializers.SerializerMethodField() class Meta: model = Content fields = ('active', 'draft', 'format', 'title', 'introduction', 'thumbnail', 'views_count', 'date_creation', 'owner', 'is_ownerz', 'category', 'slug', 'text', 'digital', 'picture', 'tags') read_only_fields = ('active', 'draft', 'format', 'title', 'introduction', 'thumbnail', 'views_count', 'date_creation', 'owner', 'category', 'slug', 'text', 'digital', 'picture', 'tags') def get_is_ownerz(self, obj): request = self.context.get('request') return obj.owner == request.user
def list(self, request): queryset = User.objects.filter(is_active=True) order_by = self.request.query_params.get('order_by', None) self.request = request if order_by == '-date_joined': queryset = User.objects.filter( deactivated=False).order_by('-date_joined') else: queryset = User.objects.filter(is_active=True) vignette_display = self.request.query_params.get( 'vignette_display', None) username = self.request.query_params.get('username', None) email = self.request.query_params.get('email', None) order_by = self.request.query_params.get('order_by', None) or 'username' statut = self.request.query_params.get('statut', None) # -*- Critères de filtre -*- if statut and statut is not None: queryset = queryset.filter(statut=statut) paginator = StreamResultsSetPagination() result_page = paginator.paginate_queryset(queryset, request) if vignette_display and vignette_display is not None: serializer = UserVignetteSerializer(result_page, context={'request': request}, many=True) else: serializer = UserSerializer(result_page, context={'request': request}, many=True) return paginator.get_paginated_response(serializer.data)
class CommentDetailSerializer(serializers.HyperlinkedModelSerializer): author = UserSerializer() class Meta: model = Comment fields = '__all__'
def get(self, request, format=None): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data)
class BranchSerializer(serializers.ModelSerializer): branch_manager = UserSerializer(read_only=True) class Meta: model = Branch fields = ('__all__')
class AnswerSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Answer fields = ('id','user', 'body')
class FavoriteSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Favorite fields = ['user']
def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class ChatSerializer(serializers.ModelSerializer): participants = UserSerializer(many=True) class Meta: model = Chat fields = ('participants', 'is_private')
def get(self, request, pk, format=None): user = self.get_object(pk) user = UserSerializer(user) return Response(user.data)
class CommentSerializer(serializers.HyperlinkedModelSerializer): author = UserSerializer() class Meta: model = Comment fields = ['id', 'text', 'author', 'created', 'modified']
def current_user(request): """ Determine the current user by their token, and return their data """ serializer = UserSerializer(request.user) return Response(serializer.data)