可写嵌套Django Serializer错误

时间:2018-02-23 16:24:45

标签: django django-rest-framework django-serializer

我有这个问题:

    class UserProfiles(models.Model):
      user = models.OneToOneField(User)
      role_alt = models.CharField(max_length=256, null=False)

    class ProfileSerializer(serializers.ModelSerializer):
      class Meta:
        model = UserProfiles
        fields = ('role_alt', )

    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)
      UserProfiles.objects.create(user=user, **profile_data)

      return user

越来越 错误:           尝试获取字段值时获得AttributeError         序列化程序profile上的UserSerializer。序列化程序字段         可能命名不正确,并且不匹配任何属性或键         User实例。原始例外文字是:'用户'宾语         没有属性'个人资料'。

1 个答案:

答案 0 :(得分:1)

ModelSerializer中的字段名称应与模型中的字段名称相同。 OneToOne字段的默认反向查找是小写的模型名称。尝试将profile重命名为userprofiles

class UserSerializer(serializers.ModelSerializer):
  userprofiles = ProfileSerializer()
  class Meta:
    model = User
    fields = ('username', 'email', 'userprofiles')

  def create(self, validated_data):
     profile_data = validated_data.pop('userprofiles')
     user = User.objects.create(**validated_data)
     UserProfiles.objects.create(user=user, **profile_data)

  return user