Answer the question
In order to leave comments, you need to log in
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
@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
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 questionAsk a Question
731 491 924 answers to any question