Django Rest框架嵌套的可写序列化器

k4emjkb1  于 2023-01-14  发布在  Go
关注(0)|答案(1)|浏览(145)

我想创建一个可写的多级串行化程序,有2个或更多的级别。但是当我使用下面的代码时。我得到响应错误请求400。当我排除TaskSerializer时,它正在工作(1Level),但嵌套更多,它不工作。我能做什么,它工作?
先谢了。

    • 查看次数. py**
class BoardView(APIView):

def get(self, request, email):
    user = User.objects.get(email=email)
    boards = Boards.objects.filter(board_creator=user.id)
    serializer = BoardsSerializer(instance=boards, many=True)
    return Response(serializer.data)

def post(self, request, email):
    response = Response()
    data = request.data['board']
    user = User.objects.filter(
        email=data['board_creator']).first()

    if user is None:
        response.data = {
            'detail': 'User not found'
        }
        response.status_code = status.HTTP_404_NOT_FOUND
        return response

    boards_by_user = Boards.objects.filter(board_creator=user.id)
    board_len = boards_by_user.filter(
        board_name=data['name'])

    if len(board_len) > 0:
        response.data = {
            'detail': 'Board already exists'
        }
        response.status_code = status.HTTP_409_CONFLICT
        return response

    data['board_creator'] = user.id
    print(data)
    serializer = BoardsSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        response.status_code = status.HTTP_201_CREATED
        response.data = {
            'detail': 'Board created successfully'
        }
        return response

    response.status_code = status.HTTP_400_BAD_REQUEST
    return response
    • 型号. py**
class Boards(models.Model):
    board_name = models.CharField(max_length=255, null=None)
    board_creator = models.ForeignKey(to=User, on_delete=models.CASCADE)

    def __str__(self) -> str:
        return str(self.board_name)

class Columns(models.Model):
    column_name = models.CharField(max_length=255, null=None)
    board = models.ForeignKey(
        to=Boards, on_delete=models.CASCADE, related_name='columns')

    def __str__(self) -> str:
        return str(self.column_name)

class Tasks(models.Model):
    task_title = models.CharField(max_length=255, null=None)
    task_description = models.TextField(null=True, blank=True)
    task_created = models.DateTimeField(default=timezone.now)
    task_finish = models.DateTimeField(null=True, blank=True)
    colmun = models.ForeignKey(
        to=Columns, on_delete=models.CASCADE, related_name='tasks')

    def __str__(self) -> str:
        return str(self.task_title)

class Subtasks(models.Model):
    subtasks_titel = models.CharField(max_length=255, null=None)
    task = models.ForeignKey(
        to=Tasks, on_delete=models.CASCADE, related_name='subtasks')
    subtask_complete = models.BooleanField(default=False)
    • 序列化程序. py**
class TaskSerializer(serializers.ModelSerializer):

    title = serializers.CharField(source='task_title')
    description = serializers.CharField(source='task_description')
    finish = serializers.DateTimeField(source='task_finish')
    #subtasks = SubtasksSerializer(many=True)

    class Meta:
        model = Tasks
        fields = ['id', 'title', 'description','finish']
        read_only_fields = ['id', 'finish']

class ColumnsSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='column_name')
    tasks = TaskSerializer(many=True)

    class Meta:
        model = Columns
        fields = ['id', 'name', 'tasks']
        read_only_fields = ['id']

    def create(self, validated_data):
        tasks = validated_data.pop('tasks')
        column = Columns.objects.create(**validated_data)
        for task_data in tasks:
            Tasks.objects.create(column=column, **task_data)
            #column.tasks.add(task)
        return column

class BoardsSerializer(serializers.ModelSerializer):

    columns = ColumnsSerializer(many=True)
    name = serializers.CharField(source='board_name')

    class Meta:
        model = Boards
        fields = ['id', 'name', 'columns', 'board_creator']
        read_only_fields = ['id']
        extra_kwargs = {
            'board_creator': {'write_only': True}
        }

    def create(self, validated_data):
        columns = validated_data.pop('columns')
        board = Boards.objects.create(**validated_data)
        for column_data in columns:
            tasks = column_data.pop('tasks')
            Columns.objects.create(board=board, **column_data)
            #board.columns.add(column)
        return board
    • 发布JSON**
{"board":{
  "name": "004dsfd5d85",
  "board_creator":"admin@admin.de", 
  "columns": [
    {"name":"TEST", "tasks":[{"title":"test"}]},
    {"name":"TEST2", "tasks":[{"title":"test"}]}
    ]}
}
0lvr5msh

0lvr5msh1#

{
  "name": "004dsfd5d85",
  "board_creator":"admin@admin.de", 
  "columns": [
    {"name": "TEST", "tasks":[{"title": "test"}]},
    {"name":"TEST2", "tasks":[{"title":"test"}]}
    ]
}

这是有效的JSON格式

相关问题