1

I have a doubt with the serializers and so far I have not been able to solve it. I explain the doubt with the following example:

I have a User model and this model has the following attributes: username, password, first_name, last_name, age, gender. I also have a serializer, which is called UserSerializer. The UserSerializer should do the following:

  • When inserting information into the database, UserSerializer should only take into account the fields: username, password, first_name, last_name.

  • When retrieving information from the database, UserSerializer should only take into account the fields: age, gender.

  • When updating the database information, UserSerializer should only take into account the fields: password.

My solution:

class UserSerializer:

    class UserCreateSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ['username', 'password', 'first_name', 'last_name']

    class UserGetSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ['age', 'gender']

    class UserUpdateSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ['password']

Question:

The question: is there any way to synthesize the three serializers into one, or what is the best solution for this problem?

Thank you very much.

1 Answer 1

0

Use write_only and read_only parameters in serializer fields to specify fields for creating and retrieving

class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(write_only=True, required=False)
    password = serializers.CharField(write_only=True)
    first_name = serializers.CharField(write_only=True, required=False)
    last_name = serializers.CharField(write_only=True, required=False)
    age = serializers.IntegerField(read_only=True)
    gender = serializers.CharField(read_only=True)


    class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'age', 'gender']

If any field is optional, then you can add the required=False

Sign up to request clarification or add additional context in comments.

2 Comments

required=False is needed for fields username, first_name and last_name to enable updating User only with a password. This answer is not responding exactly to OP requirements though, especially: > When updating the database information, UserSerializer should only take into account the fields: password.
I had already mentioned to add required=False for the optional fields. Anyway, updated the optional fields with the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.