I;ve an API endpoint that requests data in the below format:-
{
"platform": "value",
"username": "value",
"login_type": "value"
}
Now, I've a model :-
class ModelA(models.Model):
field1 = models.IntegerField()
The request variables are not the part of the model, hence I create the following serializer:-
class ModelASerializer(serializers.ModelSerializer):
username = serializers.CharField()
login_type = serializers.IntegerField()
platform = serializers.ChoiceField(choices=User.PLATFORM_CHOICES)
def create(self, data):
platform, username = data.get('platform'), data.get('username')
login_type = data.get('login_type')
###### some processing based on above input
instance = ModelA.objects.create(field1=11111)
return instance
class Meta:
model = ModelA
fields = ('username', 'login_type', 'platform')
read_only_fields = ('field1', )
When I POST
the data, the error returned back is
The serializer field might be named incorrectly and not match any attribute or key on the `ModelA` instance.
Original exception text was: 'ModelA' object has no attribute 'username'.
I understand that it tries to get_attr
the fields
from the instance object. How do I send back the response where INPUT request is different(ie unrelated to the model fields) and response is different(ie related to the model fields)?
I solved the above problem settings field as write_only = True
.
class ModelASerializer(serializers.ModelSerializer):
username = serializers.CharField(write_only = True)
login_type = serializers.IntegerField(write_only = True)
platform = serializers.ChoiceField(choices=User.PLATFORM_CHOICES, write_only = True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With