更新嵌套的多对多

时间:2022-10-05 11:39:01

I have a Serializer that looks like this:

我有一个如下所示的Serializer:

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

Where categories is a many-to-many on my model. I don't want a nested view just IDs so I used a PrimaryKeyRelatedField. So this works only if I have read_only=True which I don't want.

在我的模型中,类别是多对多的。我不希望嵌套视图只是ID,所以我使用了PrimaryKeyRelatedField。所以只有当我有read_only = True时我才不会这样做。

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

I want to run each id and add them like this to the model....

我想运行每个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

How is this possible as PrimaryKeyRelatedField want me to use ready only.

这是怎么回事,因为PrimaryKeyRelatedField希望我只使用ready。

1 个解决方案

#1


1  

You might try to subclass ModelSerializer instead of HyperlinkedModelSerializer and then supply the queryset argument for the PrimaryKeyRelatedField:

您可以尝试继承ModelSerializer而不是HyperlinkedModelSerializer,然后为PrimaryKeyRelatedField提供queryset参数:

 categories = serializers.PrimaryKeyRelatedField(many=True,
                                                 queryset=Categories.objects.all())

#1


1  

You might try to subclass ModelSerializer instead of HyperlinkedModelSerializer and then supply the queryset argument for the PrimaryKeyRelatedField:

您可以尝试继承ModelSerializer而不是HyperlinkedModelSerializer,然后为PrimaryKeyRelatedField提供queryset参数:

 categories = serializers.PrimaryKeyRelatedField(many=True,
                                                 queryset=Categories.objects.all())