我正在为我的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中执行所有卖家相关的修改,即覆盖create
和update
方法。
我重构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
方法,也会发生同样的情况。我已经搜索过,但到目前为止还没有任何线索。谢谢!
答案 0 :(得分:1)
为什么在create
方法中使用Seller
代替seller
?只需使用seller
,这是SellerSerializer
的实例,应该没问题。