更新嵌套的多对多

Updating a nested many-to-many

我有一个看起来像这样的序列化程序:

{
    "id": 97, 
    "categories": [
        23,
        18
    ], 
}, 

我的模型上的类别是 many-to-many。我不想要只有 ID 的嵌套视图,所以我使用了 PrimaryKeyRelatedField。所以只有当我有我不想要的 read_only=True 时,这才有效。

Relational field must provide a `queryset` argument, or set read_only=`True`.

我想 运行 每个 id 并像这样将它们添加到模型中....

class ItemsSerializer(serializers.HyperlinkedModelSerializer):

    categories = serializers.PrimaryKeyRelatedField(many=True)


    def create(self, validated_data):

        categories = validated_data.pop('categories')
        instance = Items.objects.create(**validated_data)
        for ID in categories:
            add to model
            cat_instance = category.objects.get(id=ID)
            then add to cat_instance etc

这怎么可能,因为 PrimaryKeyRelatedField 想让我只使用 ready。

您可以尝试继承 ModelSerializer 而不是 HyperlinkedModelSerializer,然后为 PrimaryKeyRelatedField:

提供查询集参数
 categories = serializers.PrimaryKeyRelatedField(many=True,
                                                 queryset=Categories.objects.all())