如何更改 Django 中的查询集?

问题描述 投票:0回答:1

我尝试更改 Django 序列化器的输出。

基于类的视图具有函数 get_projects,它返回 Contract 实例的查询集。

ContractProject的关系是一对多:

class Contract(models.Model):
    project = models.ForeignKey(Project)

现在我有了这样的MySerializer

class MySerializer(serializers.Serializer):
    project_guid = serializers.UUIDField(source='guid')
    project_name = serializers.CharField(source='name')
    contract_guid = serializers.UUIDField(source='guid')
    contract_number = serializers.CharField(source='number')

MySerializer 的响应是:

[
  {
    "projectGuid": "project_guid_1",
    "projectName": "project_name_1",
    "contractGuid": "contract_guid_1",
    "contractNumber": "contract_number_1"
  },
  {
    "projectGuid": "project_guid_1",
    "projectName": "project_name_1",
    "contractGuid": "contract_guid_2",
    "contractNumber": "contract_number_2"
  },
  {
    "projectGuid": "project_guid_2",
    "projectName": "project_name_2",
    "contractGuid": "contract_guid_4",
    "contractNumber": "contract_number_4"
  },
  {
    "projectGuid": "project_guid_2",
    "projectName": "project_name_2",
    "contractGuid": "contract_guid_5",
    "contractNumber": "contract_number_5"
  },
]

我想将序列化器输出更改为这样的结构:

[
 {
  "project_guid": "project_guid_1",
  "project_name": "project_name_1",
  "contracts": [
    {
      "contract_guid": "contract_guid_1",
      "contract_number": "contract_number_1",
    },
    {
      "contract_guid": "contract_guid_2",
      "contract_number": "contract_number_2",
    },
    ....
  ]
 },
 {
  "project_guid": "project_guid_2",
  "project_name": "project_name_2",
  "contracts": [
    {
      "contract_guid": "contract_guid_4",
      "contract_number": "contract_number_4",
    },
    {
      "contract_guid": "contract_guid_5",
      "contract_number": "contract_number_5",
    },
    ....
  ]
 },
]

我该怎么做?

python django serialization
1个回答
0
投票

为此你可以尝试这个

class ContactSerializer(serializers.ModelSerializer):
    class Meta:
       model = Contract
       fields = ["contract_guid", "contract_number"]

class ProjectSerializer(serializers.ModelSerializer):
    contracts = ContactSerializer(many=True)
    class Meta:
        model = Project 
        fields = ["project_guid", "project_name", "contracts"]

仅此而已

© www.soinside.com 2019 - 2024. All rights reserved.