Django Rest Framework序列化程序以及相关表中的字段

时间:2018-11-04 01:48:17

标签: django django-rest-framework

我有以下型号:

class Workflow(models.Model):
    name = models.CharField(max_length=200)


class Task(models.Model):
    name = models.CharField(max_length=200)


class TaskParameter(models.Model):
    default_value = models.CharField(max_length=1000, null=True)
    name = models.CharField(max_length=200)
    task = models.ForeignKey(Task, related_name='parameters', on_delete=models.CASCADE, null=True)


class WorkflowTask(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE)
    workflow = models.ForeignKey(Workflow, related_name='workflow_tasks', on_delete=models.CASCADE, null=True)


class WorkflowTaskParameter(models.Model):
    value = models.CharField(max_length=1000)
    workflow_task = models.ForeignKey(WorkflowTask, on_delete=models.CASCADE, related_name='workflow_task_parameters', null=True)
    task_parameter = models.ForeignKey(TaskParameter, on_delete=models.CASCADE, related_name='+')

因此,基本上我想做的是让工作流程包含任务(使用WorkflowTask关联表),而那些任务具有参数(TaskParameter)。这些参数有一个默认值,但我希望能够用另一个参数覆盖此默认值(这就是WorkflowTaskParameter表的用途)。

这是我的序列化器:

class TaskParameterSerializer(serializers.ModelSerializer):
    class Meta:
        model = TaskParameter
        fields = ('name', 'default_value')

class WorkflowTaskParameterSerializer(serializers.ModelSerializer):
    name = serializers.StringRelatedField(many=False) # here i want the name from the associated TaskParameter

    class Meta:
        model = WorkflowTaskParameter
        fields = ('name', 'value')

class WorkflowTaskSerializer(serializers.ModelSerializer):
    task = serializers.StringRelatedField(many=False)
    workflow_task_parameters = WorkflowTaskParameterSerializer(many=True, read_only=True)

    class Meta:
        model = WorkflowTask
        fields = ('task', 'workflow_task_parameters')

class WorkflowSerializer(serializers.ModelSerializer):
    workflow_tasks = WorkflowTaskSerializer(many=True, read_only=True)

    class Meta:
        model = Workflow
        fields = ('name', 'workflow_tasks')

我几乎要得到想要的结果:

  {
    "name": "MyWorkflow",
    "workflow_tasks": [
      {
        "task": "MyTask",
        "workflow_task_parameters": [
          {
            // missing the task parameter name here
            "value": "myoverridedvalue"
          }
        ]
      }
    ]
  }

如评论中所述,即使我在StringRelatedfield中放入了“名称” WorkflowTaskParameterSerializer,为什么任务参数名称也没有出现在结果中?这是设计问题吗?

1 个答案:

答案 0 :(得分:1)

更改为

name = serializers.CharField(source='task_parameter.name')