如何转换为完整的JSON

时间:2018-09-12 15:28:30

标签: python django django-rest-framework

如何转换为JSON类型格式。 您需要获取有关它的完整信息,而不是对象ID。 从这样

[
  {
    "title": "scenario factory - sump",
    "scenario_pipeline": [
      {
        "pipeline": 11
      }
    ],
   "scenario_exist": [
      {
        "factory": 43
      },
      {
        "factory": 44
      }
    ]
  }
]

要这样

[
  {
    "title": "scenario factory - sump",
    "scenario_pipeline": [
      {
        "title": "factory - sump",
        "percent": 11,
        "start_point": [
          57.332892983304895,
          36.40013349999995
        ],
        "end_point": [
          51.829824506973154,
          43.43138349999996
        ],
        "point": []
      }
    ],
   "scenario_exist": [
      {
        "id": 43,
        "title": "factory",
        "choice": "Factory",
        "address": [
          57.332892983304895,
          36.40013349999995
        ]
      },
      {
        "id": 44,
        "title": "sump",
        "choice": "Sump",
        "address": [
          51.829824506973154,
          43.43138349999996
        ]
      }
    ]
  }
]

我的models.py 场景的基本模型,剩下的两个内联

class Scenario(models.Model):
    title = models.CharField(max_length=200)

class ScenarioExist(models.Model):
    scenario = models.ForeignKey('Scenario', related_name='scenario_exist', on_delete=models.CASCADE)
    factory = models.ForeignKey('factory.Factory', related_name='factory', on_delete=models.CASCADE)

class PipelineTwo(models.Model):
    scenario = models.ForeignKey('Scenario', related_name='scenario_pipeline', on_delete=models.CASCADE)
    pipeline = models.ForeignKey('pipeline.Pipeline', null = True, on_delete=models.CASCADE, related_name = 'point_two')

如果要显示访问字段的模型,我将显示。

我的serializes.py

class PipelineTwoSerializer(serializers.ModelSerializer):

    class Meta:
        model = PipelineTwo
        fields = ['pipeline']

class ScenarioExistSerializer(serializers.ModelSerializer):

    class Meta:
        model = ScenarioExist
        fields = ['factory']

class ScenarioSerializer(serializers.ModelSerializer):
    scenario_pipeline = PipelineTwoSerializer(many=True)
    scenario_exist = ScenarioExistSerializer(many=True)

    class Meta:
        model = Scenario
        fields = ['title', 'scenario_pipeline', 'scenario_exist']

1 个答案:

答案 0 :(得分:1)

您在ScenarioSerializer中使用嵌套的序列化程序;您需要在PipelineTwoSerializer中执行相同操作,以从pipeline.Pipeline获取值,在ScenarioExistSerializer中获取factory.Factory的值。