django rest框架保存M2M关系

时间:2018-07-25 12:32:14

标签: django django-models django-rest-framework

我正在尝试创建一个具有m2m关系的购物车,在保存该对象时,序列化程序会引发两个怪异的异常,如果我将关系更改为一对多,则一切正常!。

  

AttributeError:尝试在序列化程序quantity上获取字段ItemSerializer的值时,出现AttributeError。   序列化程序字段的名称可能不正确,并且与BranchItemList实例上的任何属性或键都不匹配。   原始异常文本为:“ BranchItemList”对象没有属性“ quantity”。

     在/ api / carts / 29处的

AttributeError   尝试获取序列化程序item_list上字段ItemSerializer的值时,出现AttributeError。   序列化程序字段的名称可能不正确,并且与BranchItemList实例上的任何属性或键都不匹配。   原始异常文本为:“ BranchItemList”对象没有属性“ item_list”。

我的输入:

{
    "items":[
        {"item_list":350,"price":10,"quantity":20},
        {"item_list":300,"price":10,"quantity":20}
        ]
}

型号:

enter image description here

序列化器:

enter image description here

1 个答案:

答案 0 :(得分:1)

由于您将Role模型用于M2M,因此实际上需要在序列化器中使用through模型,但是Cart的ItemCart M2M管理器返回items。要纠正错误,请指定BranchItemList

source='itemcart_set'
相关问题