Python serializer one universal function

Question:

Please help! The reviewer wants me to correct my code. I have such a code structure . He wants me to move this line (‘if request is None or request.user.is_anonymous: return False’) to a separate code structure (function or class).

class CustomUserSerializer(UserSerializer):
""" Сериализатор модели пользователя. """

is_subscribed = serializers.SerializerMethodField(read_only=True)

class Meta:
    model = User
    fields = [
        'id',
        'email',
        'username',
        'first_name',
        'last_name',
        'is_subscribed'
    ]

def get_is_subscribed(self, obj):
    request = self.context.get('request')
    if request is None or request.user.is_anonymous:
        return False
    return Subscription.objects.filter(
        user=request.user, author=obj
    ).exists()

class RecipeSerializer(serializers.ModelSerializer):

`

    def get_is_subscribed(self, obj):
        request = self.context.get('request')
        if request is None or request.user.is_anonymous:
            return False
        return Subscription.objects.filter(
            user=request.user, author=obj
        ).exists()

I do not know how to do it correctly.
Asked By: Rinat

||

Answers:

Moving a piece of code into a function or method is a common refactoring pattern. You can also move it to a class, but in your particular case, that would not make too much sense since it’s a very simple expression and classes aren’t meant for such simple expressions.

After you move the boolean expression into a function, you will have something like this:

def is_request_none_or_from_anonymous_user(request):
    return request is None or request.user.is_anonymous
...
def get_is_subscribed(self, obj):
    request = self.context.get('request')
    if is_request_none_or_from_anonymous_user(request):
        return False
    return Subscription.objects.filter(
        user=request.user, author=obj
    ).exists()
...

The next line, return False cannot be moved because we want to return from get_is_subscribed, not from anywhere else.

Answered By: user3738870
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.