DjangoRest序列化程序:保存Foreignkey关系并序列化

时间:2016-10-11 07:10:20

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

我是Django休息和序列化概念的新手

我有这种数据库结构

用户1-> N地址, 用户1-> N电话

User是一个django.contrib.auth.models.User。 AddressPhone两个模型都包含此字段user_id = models.ForeignKey(User, on_delete=models.CASCADE)

在我的UserSerializer中看起来像这样

class UserSerializer(serializers.ModelSerializer):

    address = AddressSerializer(many=False)
    phone = PhoneSerializer(many=False)

    class Meta:
        model = User
        fields = (
            'id', 'username',
            'first_name', 'last_name',
            'email', 'password',
            'address', 'phone')

    def create(self, validated_data):
        # Save user.
        user = User.objects.create(
                first_name=validated_data['first_name'],
                last_name=validated_data['last_name'],
                username=validated_data['username'],
                email=validated_data['email'],
            )
        user.set_password(validated_data['password'])
        user.save()
        # User's address
        address_data = validated_data['address']
        address_data['user_id'] = user.id
        address = Address.objects.create(**address_data)
        # User's phone
        phone_data = validated_data['phone']
        phone_data['user_id'] = user.id
        phone = Phone.objects.create(**phone_data)
        return user

和AddressSerializer:

class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = (
                'user_id', 'address', 'pin_code', 'state', 'city', 'country')

我可以创建User,但在执行serializer.data时我收到此错误:

AttributeError: Got AttributeError when attempting to get a value for field `address` on serializer `UserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'address'.

编辑:

我的create方法看起来像这样

def create(self, validated_data):
    password = validated_data.pop('password')
    validated_data['username'] = validated_data['email']
    user = User.objects.create(**validated_data)
    user.set_password(password)
    user.save()
    return user

1 个答案:

答案 0 :(得分:1)

如果您未明确指定address_set,则应拨打地址和电话字段phone_setrelated_name

class UserSerializer(serializers.ModelSerializer):
    address_set = AddressSerializer(many=False)
    phone_set = PhoneSerializer(many=False)

    class Meta:
        model = User
        fields = (
            'id', 'username',
            'first_name', 'last_name',
            'email', 'password',
            'address_set', 'phone_set'
        )

class UserSerializer(serializers.ModelSerializer):
    address = AddressSerializer(many=False, source='address_set')
    phone = PhoneSerializer(many=False, source='phone_set')

    class Meta:
        model = User
        fields = (
            'id', 'username',
            'first_name', 'last_name',
            'email', 'password',
            'address', 'phone'
        )