ValueError: “needs to have a value for field ”id“ before this many-to-many relationship can be used”

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010377372/article/details/80614030

产生这个错误的原因是,在关联多对多关系时需要id,因为在数据库中多对多关系结构如下:

所以如果 直接使用 Model.objects.create(**data)创建时,如果Model中包含多对多关系,那么就会报错:

ValueError: “needs to have a value for field ”id“ before this many-to-many relationship can be used”

解决办法是,先把data中的多对多数据取出,然后创建model,最后建立多对多关系。

示例代码:

def create(self, validated_data):
    images = validated_data.pop('image')
    production = Production.objects.create(**validated_data)
    for image in images:
        production.image.add(image)
    return production

猜你喜欢

转载自blog.csdn.net/u010377372/article/details/80614030