[英]How can I serialize the OneToOneField to be list in Django-Rest-Framework?
How can I serialize the OneToOneField to be list? 如何序列化要列出的OneToOneField?
I have two Model: 我有两个模型:
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)
You see, they are OneToOne relationship. 您会看到,它们是OneToOne关系。
In the SwitchesPortSerializer, I only can set the physical_server
many=False
: 在SwitchesPortSerializer中,我只能将physical_server
设置为many=False
:
class SwitchesPortSerializer(ModelSerializer):
"""
SwitchesPort
"""
server = ServerSerializer(many=False, read_only=True)
class Meta:
...
If I set True there will reports error, because they are one to one relationship. 如果我设置为True,则将报告错误,因为它们是一对一的关系。 The result will be like this: 结果将是这样的:
[
{
"name": "switches_port01",
"profile":"",
"server": {
"name": "server01",
...
}
},
...
]
But, I want to get the physical_server
as a JSON list, not the JSON object, how can I do that in Django-Rest-Framework? 但是,我想将physical_server
作为JSON列表而不是JSON对象获取,如何在Django-Rest-Framework中做到这一点?
My requirement data is like this: 我的需求数据是这样的:
[
{
"name": "switches_port01",
"profile":"",
"server": [
{
"name": "server01",
...
}
]
},
...
]
Although the relationship is one-to-one, I still want to get the list, not the object. 尽管关系是一对一的,但我仍然想要获取列表,而不是对象。
Is it feasible to get that? 可行吗?
You can override to_representation
method from serializer class 您可以从序列化程序类重写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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.