目前,我的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呢?请注意,如果可能的话,我希望避免在数据库中创建其他表.