简体   繁体   中英

Django REST Framework - Custom JSON

How do I serialize a list into a JSON object? The list combine 2 different models and looks like the following:

[<Room: 303 at 123 Toronto Street>, 
<Room: 305 at 123 Toronto Street>, 
<Room: 304 at 123 Toronto Street>, 
<SubvisitClinician: kchung>, 
<SubvisitClinician: pche>, 
<SubvisitClinician: mlo>]

I've created the RoomSerializer and SubvisitClinicianSerializer, but not sure to how finish it and implement it.

class RoomSerializer(serializers.ModelSerializer):
    id = serializers.Field()  # Note: `Field` is an untyped read-only field.
    name = serializers.CharField(max_length=255)
    type = serializers.Field(source='type')
    clinic_location = serializers.Field(source='clinic_location')
    status = serializers.Field(source='status')
    url = serializers.CharField(max_length=100, default="room")

    class Meta:
        model = Room

class SubvisitClinicianSerializer(serializers.ModelSerializer):
    id = serializers.Field()
    subvisit = serializers.Field('subvisit')
    user = serializers.Field('user')
    primary = serializers.BooleanField()

    class Meta:
        model = SubvisitClinician

I wrote this quickly out of memory.

Simple example:

data1 = RoomSerializer(self.get_queryset(), many=True).data
data2 = SubvisitClinicianSerializer(self.get_queryset(), many=True).data
data_list = data1 + data2

You can write function which will iterate over list and call needed serializer based on type:

def serialize_list(data):
    return [RoomSerializer(i) if isinstance(i, Room) else SubvisitClinicianSerializer(i) for i in data]

Thanks for the response Alex. Managed to answer my own question after doing some more research. Reiterated how the list was created and turned it into an object. Created a RoomList class with rooms and subvisit_clinicians, then created a RoomListSerializer. Code is below.

class RoomList(object):
    def __init__(self):
        super(RoomList, self).__init__()
        self.rooms = []
        self.subvisit_clinicians = []

    def add_room(self, room):
        self.rooms.append(room)

    def add_subvisit_clinician(self, subvisit_clinician):
        self.subvisit_clinicians.append(subvisit_clinician)

class RoomListSerializer(serializers.Serializer):
    rooms = RoomSerializer(many=True)
    subvisit_clinicians = SubvisitClinicianSerializer(many=True)

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