我试图通过在类的扩展中使用 ModelSerializer 的 create 方法来节省一些工作,然后在扩展中添加我需要的额外字段。但是,当我这样做时,我从 DRF 收到关于不支持嵌套序列化程序中的可写字段的错误。有什么方法可以实现这一点,这样我就不必在 create 方法中显式定义每个字段,而是将该工作推送到超级构造函数中?包括我的代码:
class CreateUserSerializer(ModelSerializer):
school = SchoolSerializer(required=False)
class Meta:
model = User
fields = ('id', 'username', 'password', 'first_name', 'last_name',
'user_type', 'school', 'email')
extra_kwargs = {
'password': {'write_only': True},
'user_type': {'read_only': True}
}
def create(self, validated_data):
original_validated_data = validated_data.copy()
if 'password' in validated_data:
password = validated_data.pop('password')
user = super(CreateUserSerializer, self).create(validated_data)
if 'password' in original_validated_data:
user.set_password(original_validated_data['password'])
if 'school' in original_validated_data:
user.user_type = User.TYPE_ADVISOR
return user
这是我得到的错误:
File "/serializers/user.py", line 41, in create
user = super(CreateUserSerializer, self).create(validated_data)
File "/lib/python2.7/site-packages/rest_framework/serializers.py", line 832, in create
raise_errors_on_nested_writes('create', self, validated_data)
File "/lib/python2.7/site-packages/rest_framework/serializers.py", line 724, in raise_errors_on_nested_writes
class_name=serializer.__class__.__name__
AssertionError: The `.create()` method does not support writable nestedfields by default.
Write an explicit `.create()` method for serializer `api.serializers.user.CreateUserSerializer`, or set `read_only=True` on nested serializer fields.
我正在使用 Rest Framework V3.3.1