使用REST Framework,在发布POST时我收到以下错误...
TypeError at /api/profiles/
'attribute_answers' is an invalid keyword argument for this function
PUT似乎没有任何问题。
串行
class ProfileSerializer(serializers.ModelSerializer):
user = serializers.SlugRelatedField(slug_field='username')
attribute_answers = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Profile
depth = 2
fields = ('id', 'name', 'active', 'type', 'user', 'attribute_answers')
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance.
"""
if instance:
# Update existing instance
instance.name = attrs.get('name', instance.name)
instance.active = attrs.get('active', instance.active)
instance.type = attrs.get('type', instance.type)
instance.attribute_answers = attrs.get('attribute_answers', instance.attribute_answers)
return instance
# Create new instance
return Profile(**attrs)
答案 0 :(得分:3)
您的restore_object
方法错误地尝试将attribute_answers
传递给Profile
构造函数。
实际上,由于您使用的是ModelSerializer
,因此根本不需要restore_object
方法 - 将为您处理模型实例还原。只有基本restore_object
类才需要Serializer
方法。