我们接着上节的说
上节课我们写完代码时候 尝试着去修改购物车数量,然后他报错了
我点update就报错
为毛它要我实现update()函数 ?Serializer没有帮我搞定么?
= =还真没有 意思要我自己来? 好吧
class ShopCartSerializer(serializers.Serializer):
def update(self, instance, validated_data):
#修改商品数量 instance 其实是值model(ShoppingCart)的实例
instance.nums = validated_data["nums"]
instance.save()
return instance
这样就可以了。 对了 在viewset那边需要添加一个跟用户收藏那里同样的代码:
class ShoppingCartViewset(viewsets.ModelViewSet):
lookup_field = "goods_id"
这样显示出来的才是goods的ID 而不是表自动生成的id
代码写完 测试下
搞定
贴下ModelSerializer的update函数代码
# ModelSerializer
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# Note that unlike `.create()` we don't need to treat many-to-many
# relationships as being a special case. During updates we already
# have an instance pk for the relationships to be associated with.
for attr, value in validated_data.items():
if attr in info.relations and info.relations[attr].to_many:
field = getattr(instance, attr)
field.set(value)
else:
setattr(instance, attr, value)
instance.save()
return instance
所以 还是ModelSerializer方便 能用它就尽量用它吧