gpt4 book ai didi

python - Django 序列化器输出作为 JSON 对象的一部分

转载 作者:太空宇宙 更新时间:2023-11-04 07:27:34 24 4
gpt4 key购买 nike

上下文

我有 2 个模型:CustomerDeviceGroup

目前我有一个 API 端点 /api/v1/device-groups/?customer_uuid=<customer_uuid>,它返回与给定 DeviceGroups 相关的 Customer,如下所示:

[
{
"group_uuid": "c61361ac-0826-41bb-825a-8aa8e014ae0c",
"device_group_name": "Default",
"color": "0a2f45",
"is_default": true
},
{
"group_uuid": "1a86e8e4-b41b-4f33-aefb-ce984ef96144",
"device_group_name": "Testgroup",
"color": "123456",
"is_default": false
}
]

目标

我希望 DeviceGroups 数组成为这样一个对象的一部分:

"device_groups": 
[
{
"group_uuid": "c61361ac-0826-41bb-825a-8aa8e014ae0c",
"device_group_name": "Default",
"color": "0a2f45",
"is_default": true
},
{
"group_uuid": "1a86e8e4-b41b-4f33-aefb-ce984ef96144",
"device_group_name": "Testgroup",
"color": "123456",
"is_default": false
}
]

模型

# models.py

class Customer(models.Model):
customer_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
customer_name = models.CharField(max_length=128, unique=True)


class DeviceGroup(models.Model):
group_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True)
customer_uuid = models.ForeignKey(Customer, on_delete=models.DO_NOTHING)
device_group_name = models.CharField(max_length=20)
color = models.CharField(max_length=10)
is_default = models.BooleanField(default=False)

序列化器

# serializers.py

class DeviceGroupSerializer(serializers.ModelSerializer):
class Meta:
model = DeviceGroup
fields = ('group_uuid', 'device_group_name', 'color', 'is_default')

查看

# views.py

class DeviceGroupCustomerViewSet(viewsets.ModelViewSet):
serializer_class = DeviceGroupSerializer

def get_queryset(self):
return DeviceGroup.objects.filter(customer_uuid=self.request.GET['customer_uuid'])

我尝试创建一个新的 serializer 但它没有解决我的问题:

class TestSerializer(serializers.ModelSerializer):
device_groups = DeviceGroupSerializer(many=True, read_only=True)

class Meta:
model = DeviceGroup
fields = ('device_groups', 'group_uuid', 'device_group_name', 'color', 'is_default')

我需要更改什么才能获得所需的输出?

最佳答案

你可以像这样更新你的观点

def list(self, request):
queryset = DeviceGroup.objects.filter(customer_uuid=self.request.GET['customer_uuid'])
serializer = UserSerializer(queryset, many=True)
return Response({'device_groups': serializer.data})

这将获得所需的输出..

关于python - Django 序列化器输出作为 JSON 对象的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55950079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com