Home > other >  Python serializer one universal function
Python serializer one universal function

Time:11-11

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.

CodePudding user response:

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.

  • Related