为什么我的Model Serializer的validated_data与表单输入不同?

时间:2016-08-02 02:18:40

标签: django django-rest-framework

我正在使用Django 1.8,DRF和AngularJS。我在前端有一个表格:

<form ng-submit="ctrl.add()">
    <label>Username</label>
    <input type="text" ng-model="ctrl.user.username">

    <label>Password</label>
    <input type="password" ng-model="ctrl.user.password">

    <label>Country</label>
        <select ng-model="ctrl.user.country">
            <option value="">Select your country.</option>
            <option value="USA">USA</option>
            <option value="Canada">CA</option>
        </select>

    <input type="submit" value="Register">
</form>

假设用户注册。此表单会将user.usernameuser.passworduser.country发送到后端。这是我的UserSerializer:

class UserSerializer(serializers.ModelSerializer):

    country = serializers.SlugRelatedField(slug_field='countryName', source='userextended.country', queryset=Country.objects.all())

    class Meta:
        model = User
        fields = ('username', 'password', 'country')
        read_only_field = ('country')

    def create(self, validated_data):
        user = User.objects.create_user(
            username = validated_data['username'],
            password = validated_data['password'],
        )
        UserExtended.objects.create(user=user, country=validated_data['userextended']['country'])
        return user

这是我一段时间后写的代码,它似乎有效。我的问题是关于这一行:

UserExtended.objects.create(user=user, country=validated_data['userextended']['country'])

为什么不是:

UserExtended.objects.create(user=user, country=validated_data['country'])

因为JS传递给后端的对象是user.username,user.password和user.country,而不是user.userexnteded.country。

'userextended'来自哪里?

0 个答案:

没有答案