Django DRF - 不同的请求和响应序列化

时间:2018-04-30 13:01:43

标签: python django django-rest-framework django-serializer

我有一个API端点,它以下列格式请求数据: -

{
  "platform": "value",
  "username": "value",
  "login_type": "value"
}

现在,我有一个模特: -

class ModelA(models.Model):
    field1 = models.IntegerField()

请求变量不是模型的一部分,因此我创建了以下序列化器: -

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', )

当我POST数据时,返回的错误是

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'.

我理解它会尝试get_attr来自实例对象的fields。如何在INPUT请求不同(即与模型字段无关)并且响应不同(即与模型字段相关)时发回响应?

1 个答案:

答案 0 :(得分:0)

我将上述问题设置字段解析为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)