如何使用更新功能在嵌套序列化器 Django 中添加或删除对象

How to add or remove objects in nested serializers Django using update function

我有 2 个模型 - Module 和 Room。一个模块可以有零个或多个房间,一个房间可以添加到多个模块中。因此,它们之间存在简单的多对多关系。

在使用放置请求更新模块字段时,我不想更新其中的任何房间,我只想更新模块中的 add/remove 个房间。 这是我的文件 -

module/models.py -

class Module(models.Model):
    module_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    desc = models.TextField()
    rooms = models.ManyToManyField(Rooms)

rooms/models.py -

class Rooms(models.Model):
    room_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    desc = models.TextField()
    level = models.CharField(max_length=100)
    is_deleted = models.BooleanField(default=False)

module/serializers.py -

class ModuleSerializer(serializers.ModelSerializer):
    rooms = RoomSerializer(read_only=True, many=True)
    class Meta:
        model = Module
        fields = "__all__"

    def create(self, validated_data):
        rooms_data = validated_data.pop('rooms')
        module = Module.objects.create(**validated_data)
        for data in rooms_data:
            room, created = Rooms.objects.get_or_create(**data)
            module.rooms.add(room)
        return module

rooms/serialier.py -

class RoomSerializerWrite(serializers.ModelSerializer):
    room_id = serializers.IntegerField()
    class Meta:
        model = Rooms
        fields = "__all__"

module/views.py -

class add_module(APIView):
    def post(self, request, format=None):
        module_serializer = ModuleSerializer(data=request.data)
        if module_serializer.is_valid():
            module_serializer.save()
            return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED)
        return Response(module_serializer.errors, status = status.HTTP_400_BAD_REQUEST)

POST 更新模块的请求正文 POSTMAN -

{
    "module_id": 2,
    "rooms": [
        {
            "room_id": 2,
            "title": "4",
            "desc": "22",
            "level": "2",
        }
    ],
    "title": "4",
    "desc": "22",
}

谁能帮我解决module/serializer中的更新功能?

我的理解是你不想用你的 post body 更新模块的房间,实际上你想替换它们。因此,只需从 m2m 关系中清除每个房间并根据请求添加新房间。像;

def update(self, instance, validated_data):
    # get new rooms
    rooms_data = validated_data.get('rooms')
    
    # clear m2m relationship
    instance.rooms_set.clear()
    
    # I assume your rooms_data is a list that contains dicts with room fields
    for room_data in rooms_data:
        # get room instance
        room, created = Rooms.objects.get_or_create(**room_data)
        
        # Add it to m2m relationship
        instance.rooms.add(room)
    instance.save()
    return instance
    

因此,如果您不将现有房间发送到您的序列化程序,它将在实例中从 m2m 关系中删除。