Reputation: 11
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.
Upvotes: 1
Views: 1002
Reputation: 156
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
Upvotes: 0