如何使用DRF序列化器将字段映射到不同名称的字段?

时间:2018-02-15 17:27:57

标签: python django-rest-framework

如果我有APIQuery个对象,则会给出以下表示:

{
  'key': 'Foo',
  'field_1': 'John',
  'field_2': 'Doe',
}

我正试图用模型存储它,比如

class Person(models.Model):
  key = models.CharField(max_length=255, primary_key=True)
  first = models.CharField(max_length=255)
  last = models.CharField(max_length=255)

如何正确设置序列化程序,约束APIQuery对象中的键可能会发生变化,例如field_1可能会成为field_17。我知道如果没有最后一个约束我就可以做到

class PersonSerializer(serializers.ModelSerializer):
  key = serializers.CharField()
  field_1 = serializers.CharField(source='first')
  field_2 = serializers.CharField(source='last')

1 个答案:

答案 0 :(得分:0)

使用SerializerMethodField并定义将返回姓氏的函数get_last_name

class PersonSerializer(serializers.ModelSerializer):
   key = serializers.CharField()
   field_1 = serializers.SerializerMethodField('get_first_name')
   field_2 = serializers.SerializerMethodField('get_last_name')

   class Meta:
       model = "Person"
       fields = ('key','field_1','field_2')

   def get_first_name(self, obj):
       return obj.first       

   def get_last_name(self, obj):
       return obj.last