如何将OneToOneField序列化为列表?
我有两个模型:
class SwitchesPort(models.Model):
"""
SwitchesPort
"""
name = models.CharField(max_length=32)
profile = models.CharField(max_length=256)
class Server(models.Model):
...
switchesport = models.OneToOneField(to=SwitchesPort, related_name="server", on_delete=models.DO_NOTHING, null=True)
你知道,他们是OneToOne的关系。
在SwitchesPortSerializer中,我只能设置physical_server
many=False
:
class SwitchesPortSerializer(ModelSerializer):
"""
SwitchesPort
"""
server = ServerSerializer(many=False, read_only=True)
class Meta:
...
如果我设置为True,则报告错误,因为它们是一对一的关系。 结果将是这样的:
[
{
"name": "switches_port01",
"profile":"",
"server": {
"name": "server01",
...
}
},
...
]
但是,我希望将physical_server
作为JSON列表,而不是JSON对象,我如何在Django-Rest-Framework中实现?
我的需求数据是这样的:
[
{
"name": "switches_port01",
"profile":"",
"server": [
{
"name": "server01",
...
}
]
},
...
]
虽然这种关系是一对一的,但我仍然希望获得列表,而不是对象 这样做是否可行?
答案 0 :(得分:1)
您可以从序列化程序类
覆盖to_representation
方法
class SwitchesPortSerializer(ModelSerializer):
"""
SwitchesPort
"""
physical_server = ServerSerializer(read_only=True)
def to_representation(self, instance):
ret = super().to_representation(instance)
ret['physical_server'] = [ret['physical_server']]
return ret