目前,我的Django服务器可以返回以下JSON:

[
  {
    "id": 1,
    "customer": {
      "id": 1,
      "name": "John Doe"
    },
    "description1": "...",
    "description2": "...",
    "description3": "...",
    "description4": "..."
  },
  {
    "id": 2,
    "customer": {
      "id": 1,
      "name": "John Doe"
    },
    "description1": "...",
    "description2": "...",
    "description3": "...",
    "description4": "..."
  },
  {
    "id": 3,
    "customer": {
      "id": 1,
      "name": "John Doe"
    },
    "description1": "...",
    "description2": "...",
    "description3": "...",
    "description4": "..."
  },
  {
    "id": 4,
    "customer": {
      "id": 2,
      "name": "Jane Doe"
    },
    "description1": "...",
    "description2": "...",
    "description3": "...",
    "description4": "..."
  },
  {
    "id": 5,
    "customer": {
      "id": 2,
      "name": "Jane Doe"
    },
    "description1": "...",
    "description2": "...",
    "description3": "...",
    "description4": "..."
  }
]

我的模特是:

from django.db import models

class Customer(models.Model):
    name = models.CharField(verbose_name="Customer name")

from django.db import models


class PurchaseDescriptions(models.Model):
    customer =  models.ManyToManyField("customer.Customer", related_name="customer", verbose_name="Customer")
    description1 = models.CharField(verbose_name="Description 1")
    description2 = models.CharField(verbose_name="Description 2")
    description3 = models.CharField(verbose_name="Description 3")
    description4 = models.CharField(verbose_name="Description 4")

我的序列化程序是:

from rest_framework import serializers

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = [
            "id",
            "name",
        ]

class PurchaseDescriptionsSerializer(serializers.ModelSerializer):
    customer = CustomerSerializer()
    
    class Meta:
        model = PurchaseDescriptions
        fields = [
            "id",
            "customer",
            "description1",
            "description2",
            "description3",
            "description4",
        ]

发帖主题:Re:Колибри0.7.0

from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins

class ScheduleViewSet(
    mixins.ListModelMixin,
    GenericViewSet,
):
    queryset = PurchaseDescriptions.objects.all()
    serializer_class = PurchaseDescriptionsSerializer

我想重写它,并在customer的基础上做一些群,例如

[
  {
    "customer": {
      "id": 1,
      "name": "John Doe"
    },
    "data": [
      {
        "id": 1,
        "description1": "...",
        "description2": "...",
        "description3": "...",
        "description4": "..."
      },
      {
        "id": 2,
        "description1": "...",
        "description2": "...",
        "description3": "...",
        "description4": "..."
      },
      {
        "id": 3,
        "description1": "...",
        "description2": "...",
        "description3": "...",
        "description4": "..."
      }
    ]
  },
  {
    "customer": {
      "id": 2,
      "name": "Jane Doe"
    },
    "data": [
      {
        "id": 4,
        "description1": "...",
        "description2": "...",
        "description3": "...",
        "description4": "..."
      },
      {
        "id": 5,
        "description1": "...",
        "description2": "...",
        "description3": "...",
        "description4": "..."
      }
    ]
  }
]

但我不知道如何使用Django的视图和序列化程序来实现这一点.我怎么才能得到这样的JSON呢?请注意,如果可能的话,我希望避免在数据库中创建其他表.

推荐答案

您可以覆盖序列化程序to_representation()以获得定制的JSON响应.

试一试:

class PurchaseDescriptionsSerializer(serializers.ModelSerializer):
    customer = CustomerSerializer()

    class Meta:
        model = PurchaseDescriptions
        fields = [
            "id",
            "customer",
            "description1",
            "description2",
            "description3",
            "description4",
        ]

    def to_representation(self, instance):
        data = super().to_representation(instance)
        customer_id = data["customer"]["id"]
        customer_name = data["customer"]["name"]
        del data["customer"]
        return {
            "customer": {
                "id": customer_id,
                "name": customer_name,
            },
            "data": [data],
        }

Python相关问答推荐

多处理代码在while循环中不工作

如何使用scipy从频谱图中回归多个高斯峰?

线性模型PanelOLS和statmodels OLS之间的区别

如何将ctyles.POINTER(ctyles.c_float)转换为int?

Deliveryter Notebook -无法在for循环中更新matplotlib情节(保留之前的情节),也无法使用动画子功能对情节进行动画

将数据框架与导入的Excel文件一起使用

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

从numpy数组和参数创建收件箱

numpy卷积与有效

实现自定义QWidgets作为QTimeEdit的弹出窗口

Pandas计数符合某些条件的特定列的数量

如何根据一列的值有条件地 Select 前N个组,然后按两列分组?

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

如何在达到end_time时自动将状态字段从1更改为0

使用Python异步地持久跟踪用户输入

如何在FastAPI中替换Pydantic的constr,以便在BaseModel之外使用?'

如何从数据框列中提取特定部分并将该值填充到其他列中?

将字节序列解码为Unicode字符串

在任何要保留的字段中添加引号的文件,就像在Pandas 中一样

极点用特定值替换前n行