Django用外键创建模型

时间:2017-07-21 12:14:02

标签: django django-rest-framework

我有以下模型:

class Task(models.Model):
    what_task = models.CharField(max_length=100, )

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.what_task)


class Step(models.Model):
    task = models.ForeignKey(Task, related_name='steps', on_delete=models.CASCADE, )
    what_step = models.CharField(max_length=50, blank=True, )

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.what_step)

我有序列化器:

class StepSerializer(serializers.ModelSerializer):
    class Meta:
        model = Step
        fields = '__all__'

class TaskSerializer(serializers.ModelSerializer):
    steps = StepSerializer(many=True)
    class Meta:
        model = Task
        fields = '__all__'

    def create(self, validated_data):
        steps_data = validated_data.pop('steps')
        task = Task.objects.create(**validated_data)
        for step_data in steps_data:
            Step.objects.create(task=task, **step_data)
        return task 

和我的观点:

@api_view(['GET', 'POST'])
def task_list(request):
    """
    List all tasks, or create a new task.
    """
    if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = TaskSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我期待在创建任务时,我也会在单个请求中创建它的步骤。我从前端发送的请求JSON如下所示:

{what_task: "Sample task three", steps:[{task: 0, what_step: "Test Step"}]}

这会引发{"steps":[{"task":["This field is required."]}]}错误。我究竟做错了什么?我发错了JSON吗?

PS :因为我在创建时没有任务ID,所以我发送的是0,应该是正确的值,我打算如何在后端处理它?<​​/ p >

1 个答案:

答案 0 :(得分:1)

StepSerializer期望获得Task个ID。在您的情况下,从父序列化程序(TaskSerializer)中获取它时不需要它。

只需将您的StepSerializer修改为exclude任务栏:

class StepSerializer(serializers.ModelSerializer):
    class Meta:
        model = Step
        exclude = ('task',)

如果您想要显示该字段,也可以将该字段设置为read_only,但它不一定是必需的,因为它包含在Task中。

在任何情况下,您可以在创建任务时省略task中的steps字段(无论如何,您设置的任何值都将被忽略)。