本文由Scarb发表于金甲虫的博客,转载请注明出处

DRF 在View中为不同的HTTP方法指定不同的序列化器

需求

在序列化器中添加额外域,域的值由某个函数生成。或者用于修改某个域的名称

解决方法

使用SerializerMethodField

1
2
3
4
5
6
7
8
9
class FooSerializer(serializers.ModelSerializer):
my_field = serializers.SerializerMethodField('is_named_bar')

def is_named_bar(self, foo):
return foo.name == "bar"

class Meta:
model = Foo
fields = ('id', 'name', 'my_field')

serializermethodfield

使用Model@property

1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo(models.Model):
. . .
@property
def my_field(self):
return stuff
. . .

class FooSerializer(ModelSerializer):
my_field = serializers.ReadOnlyField(source='my_field')

class Meta:
model = Foo
fields = ('my_field',)

指定Serializer或Field的source

可以为ModelField指定source数据

1
2
3
4
5
6
class ParkSerializer(serializers.ModelSerializer):
location = serializers.SomeSerializerField(source='alternate_name')

class Meta:
model = Park
fields = ('other_fields', 'location')

也可以为级联关系Serializer指定source

1
2
3
4
5
6
7
8
9
10
class ParkSerializer(serializers.ModelSerializer):
locations = AlternateNameSerializer(source='alternate_name', many=true)

class Meta:
model = Park
fields = ('other_fields', 'locations')

class AlternateNameSerializer(serializers.ModelSerialzer):
class Meta:
model = SomeModel

参考资料

  1. django-rest-framework-adding-additional-field-to-modelserializer
  2. how-to-change-field-name-in-django-rest-framework