Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DRF - Different Request and Response Serialization

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)?

like image 813
PythonEnthusiast Avatar asked Aug 31 '25 05:08

PythonEnthusiast


1 Answers

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)
like image 108
PythonEnthusiast Avatar answered Sep 02 '25 17:09

PythonEnthusiast