D
D
dert23132022-02-14 12:03:39
Django
dert2313, 2022-02-14 12:03:39

How to perform this check in the serializer?

The very essence of the question: I made a check that the user cannot subscribe to the same author 2 times in the serializer. But to call is_valid()in a view, you need to pass a parameter to the serializer data. And I don’t quite understand what needs to be passed there to call is_valid()----> for a serializer error in case of trying to subscribe 2 times.

Serializer:

class UserFollowSerializer(serializers.ModelSerializer):
    is_subscribed = serializers.SerializerMethodField()
    recipes = UserRecipeSerializer(many=True, read_only=True)
    recipes_count = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = (
            'email',
            'id',
            'username',
            'first_name',
            'last_name',
            'is_subscribed',
            'recipes',
            'recipes_count'
        )

    def get_is_subscribed(self, obj):
        user = self.context.get('user')
        return user.follower.filter(author=obj).exists()

    def get_recipes_count(self, obj):
        return obj.recipes.count()

    def validate(self, data):
        author = get_object_or_404(User, self.context.get['pk'])
        if Follow.objects.filter(
            user=self.context['request'].user,
            author=author
        ).exists():
            raise serializers.ValidationError(
                'Вы уже подписаны на этого автора'
            )
        return data


View:
@action(
        detail=True,
        methods=('post', 'delete'),
        permission_classes=(IsAuthenticated,),
    )
    def subscribe(self, request, pk):
        author = get_object_or_404(User, pk=pk)
        if request.method == 'POST':
            if author == request.user:
                return Response(
                    {'errors': 'Вы пытаетесь подписаться на себя'},
                    status=status.HTTP_400_BAD_REQUEST,
                )
            serializer = UserFollowSerializer(
                author,
                # data=?
                context={
                    'request': request,
                }
            )
            serializer.is_valid(raise_exception=True)
            Follow.objects.create(user=request.user, author=author)
            return Response(
                serializer.data,
                status=status.HTTP_201_CREATED
                )
        Follow.objects.filter(user=request.user, author=author).delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Web Dentist, 2022-02-16
@kgb_zor

0. Go read the documentation
1. is_valid() is not used in conjunction with a passed class instance
2. It is incorrect to implement such logic, write @classmethod for Follow, in which you will check your condition

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question