来自django rest框架网站示例我写了我的usererializer.py,我的profileserializer就是这样:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ['facebook_id', 'facebook_token', 'push_device_token', 'photo', 'status', 'level']
class UserSerializer(serializers.ModelSerializer):
profile = ProfileSerializer()
class Meta:
model = User
fields = ('username', 'email', 'profile')
def create(self, validated_data):
profile_data = validated_data.pop('profile')
user = User.objects.create(**validated_data)
Profile.objects.create(user=user, **profile_data)
return user
和I'am以这样的方式发送JSON请求:
{
"username":"admin",
"email":"e@e.com",
"password":12345678,
"profile":{
"status":1,
"level":1,
"facebook_id":1,
"facebook_token":1,
"push_device_token":1,
"photo":"url.com"
}
}
,但我只会得到错误:
尝试在序列化器
UserSerializer
上获得字段profile
的值时获得属性。序列化器字段可能被错误地命名,并且在
User
实例上不匹配任何属性或键。原始异常文本是:'用户'对象没有属性'profile'。
我认为这可能是缺乏对用户模型的参考。假设您的个人资料模型看起来像:
class Profile(models.Model):
user = models.ForeignKey(User)
模型用户将具有profile_set
属性,而不是profile
。调整此使用相关信息:
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile')