因为我对django很新,所以很遗憾地提出一个我无法弄清楚的基本问题。
我有这样的序列化器
class UserProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = UserProfile
fields = ('id', 'user')
def create(self, validated_data):
print validated_data['user']
user = User.objects.create_user(**validated_data['user'])
user_profile, created = UserProfile.objects.get_or_create(user=user)
return user
def get_identifier(self):
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
我有来自视图的名称,电子邮件,密码,phoneNumber等字段,如果我打印validated_data ['user']
,我会给出这样的数据[(u'email', u'tes1@c.vom11'), (u'name', u'rohdaasais'), (u'password', u'rokl'), (u'phoneNumber', u'2323')])
现在我想在保存之前在此用户中添加一个标识符 所以它应该像这样
[(u'email', u'tes1@c.vom11'), (u'name', u'rohdaasais'), (u'password', u'rokl'), (u'phoneNumber', u'2323'),(u'identifier', u'SJAJK77')])
但是当我这样做时
validated_data['user']['identifier'] = self.get_identifier()
它没有用,并说我正在尝试访问不存在的字段,如何将其添加到用户字典
编辑:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'name', 'password', 'picture', 'phoneNumber')
def create(self, validated_data):
validated_data['identifier'] = self.get_identifier()
validated_data['password'] = make_password(validated_data['password'])
user = super(UserSerializer, self).create(validated_data)
return user
def get_identifier(self):
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(7))
我已编辑了该问题,并显示了UserSerializer