如何在不同的应用程序中正确创建/更新Serializers中的对象

时间:2016-01-05 12:48:27

标签: python django django-rest-framework

我正在为我的Django项目开发REST API。我有两个应用程序(帐户和卖家)的项目工作版本,但它执行AccountSerializer中的所有逻辑,如下所示:

帐户/ serializers.py

class AccountSerializer(serializers.ModelSerializer):
    seller = SellerSerializer(required=False)

    class Meta:
        model = Account
        fields = ('id', 'email', 'password', 'seller',)
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        account = Account.objects.create(email=validated_data['email'])
        account.set_password(validated_data['password'])
        account.save()
        Seller.objects.create(account=account)

        return account

    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()

        seller = instance.seller
        seller_data = validated_data.pop('seller')
        seller.birth_date = seller_data.get('seller', seller.birth_date)
        seller.save()

        return instance

卖家/ serializers.py

class SellerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Seller
        fields = ('birth_date',)

由于与卖家信息相关的逻辑在AccountSerializer中,我认为将其转移到SellerSerializer可能是有意义的(为了增强脱钩)我试图在SellerSerializer中执行所有卖家相关的修改,即覆盖createupdate方法。

我重构update方法如下:

帐户/ serializers.py

class AccountSerializer(serializers.ModelSerializer):
    seller = SellerSerializer(required=False)
    [...]
    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.set_password(validated_data.get('password', instance.password))
        instance.save()

        # Update Seller related fields
        if 'seller' in validated_data:
            seller_data = validated_data['seller']
            self.seller.update(validated_data=seller_data)

卖家/ serializers.py

class SellerSerializer(serializers.ModelSerializer):
    [...]
    def update(self, instance, validated_data):
        instance.birth_date = validated_data.get('birth_date',
                                                 instance.birth_date)
        instance.save()

    return instance

但是我收到以下错误:

AttributeError:' AccountSerializer'对象没有属性'卖方'

如果我尝试覆盖create方法,也会发生同样的情况。我已经搜索过,但到目前为止还没有任何线索。谢谢!

1 个答案:

答案 0 :(得分:1)

为什么在create方法中使用Seller代替seller?只需使用seller,这是SellerSerializer的实例,应该没问题。