0

我有以下简单的待办事项列表模型:

class TodoList(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=255)


class Todo(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    todo_title = models.CharField(max_length=64)
    todo_body = models.TextField()
    completed = models.BooleanField(default=False)
    list = models.ForeignKey(TodoList, on_delete=models.CASCADE, related_name='messages')

我想做的是使用drf-nested-routers设置嵌套路由。例如:

/api/v1/todo-lists/                           <- List Todo Lists
/api/v1/todo-lists/{LIST_ID}/                 <- CRUD a Todo list
/api/v1/todo-lists/{LIST_ID}/todos/           <- List todos for a particular list
/api/v1/todo-lists/{LIST_ID}/todos/{TODO_ID}/ <- CRUD for a particular todo

我有一个 Todo 序列化器:

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Todo
        fields = ('id', 'todo_title', 'todo_body', 'completed', 'list',)
        read_only_fields = ('id', 'list',)

还有一个 TodoByList 视图集:

class TodoByListViewSet(mixins.CreateModelMixin,
                        mixins.ListModelMixin,
                        viewsets.GenericViewSet):
    serializer_class = TodoSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return Todo.objects.filter(list_id=self.kwargs['todolist_pk'])

    def create(self, request, todolist_pk=None):
        todo_list = get_object_or_404(TodoList, pk=todolist_pk)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

列表视图效果很好,但是对于创建我有点赶上 22。我的 Todo 模型的 list 参数是必需的(这是正确的),因此由于未设置perform_create而不起作用。list但是,如果我listread_only_fields序列化程序中删除,则会.is_valid失败,因为我没有将列表 ID 与我的请求数据一起传递。我需要做的是注入todo_list从 url 参数中检索到的实例,但我不确定如何做到这一点。

4

1 回答 1

0

您需要从序列化程序中的read_only_fields中删除列表。然后你需要将 todo_list id 传递给序列化程序。例如:

def create(self, request, todolist_pk=None):
    todo_list = get_object_or_404(TodoList, pk=todolist_pk)
    dict_data = dict(request.data)
    dict_data['list'] = todo_list.id
    serializer = self.get_serializer(data=dict_data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
于 2019-08-13T09:48:25.157 回答