Reputation: 666
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
Upvotes: 0
Views: 826
Reputation: 666
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)
Upvotes: 0
Reputation: 2423
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
Upvotes: 3
Reputation: 6065
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]
Upvotes: 0