如何获取 Django 的 ManyToManyField 的输入?

How to take input of ManyToManyField of django?

我有 2 个模型 - 房间和模块。一个模块可以包含多个房间,一个房间可以包含多个不同的模块。以下是模型 -

房间模型 -

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)

模块型号-

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

模块序列化器-

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

模块view.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("response":module_serializer.errors, status = status.HTTP_400_BAD_REQUEST)

如何在创建我的模块对象时将多个房间作为 views.py 文件的输入。此外,如果我想在邮递员中测试我的 API,那么我如何在邮递员中进行多个输入。

您可以使用类似的结构:

class ModuleSerializer(serializers.ModelSerializer):
   rooms = RoomSerializer(read_only=True, many=True)


   class Meta:
       model = Module
       fields = "__all__"


   def create(self, validated_data):
       rooms = validated_data.pop('rooms')
       ...
       for room in rooms:
           ...
       return Response(...)