Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python serializer one universal function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading