简体   繁体   中英

How can I serialize the OneToOneField to be list in Django-Rest-Framework?

How can I serialize the OneToOneField to be list?

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.

In the SwitchesPortSerializer, I only can set the 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. 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM