【发布时间】:2017-03-06 22:04:41
【问题描述】:
从 django rest 框架站点示例中,我编写了我的 UserSerializer.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
我正在发送这样的 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的值时出现 AttributeError。序列化器字段可能命名不正确,并且与
User实例上的任何属性或键都不匹配。原始异常文本是:“用户”对象没有属性“配置文件”。
【问题讨论】:
-
我希望您不应该在字段列表中包含个人资料,因为它实际上不是模型上的字段。
-
你有没有尝试打印验证数据...也放了完整的回溯
-
@DanielRoseman 在字段列表中没有个人资料,我收到以下错误:
The field 'profile' was declared on serializer UserSerializer, but has not been included in the 'fields' option. -
请显示
ProfileSerializer。 -
尝试将其从字段以及声明 profile = ProfileSerializer() 中删除。它应该可以工作,因为序列化程序中没有其他依赖 b/w 两个模型。
标签: python json django rest django-rest-framework