How To Change Serialized JSON Structure Django Rest Framwork
I'm wondering if it possible to change structure of my JSON that im sedinding out. currenyly it looks like this: { 'para_subject': { 'discipline': 'MATAN' }, 'par
Solution 1:
It depends of the serializers/models you use, but in general can use serializers looking like this:
class Serializer1(serializers.Serializer):
discipline = serializers.CharField()
room = serializers.IntegerField()
para_professer = Serializer2()
class Serializer2(serializers.Serializer):
username = serializers.CharField()
email = serializers.CharField()
first_name = serializers.CharField()
last_name = serializers.CharField()
middle_name = serializers.CharField()
Here you can find the nested serializer doc of the django rest framework http://www.django-rest-framework.org/api-guide/relations/#nested-relationships
Based on the new infos in your question you could overwrite the .to_representation() method of your serializer:
class ParaSerializer(serializers.ModelSerializer):
class Meta:
model = Para
fields = (
'para_subject',
'para_room',
'para_professor',
'para_number',
'para_day',
'para_group',
'week_type'
)
def to_representation(self, instance):
return {
'discipline': instance.para_subject.name,
'room': instance.para_room.number,
'para_professor': {
'username': instance.para_professor.username,
'email': instance.para_professor.email,
'first_name': instance.para_professor.first_name,
'last_name': instance.para_professor.last_name,
'middle_name': instance.para_professor.middle_name
}
}
Solution 2:
You can add discipline and room fields with source parameters on ParaSerializer.
These fields will fetch the value from the source mentioned and will be included in the output.
class ParaSerializer(serializers.ModelSerializer)
# define 'discipline' and 'room' fields
discipline = serializers.CharField(source='para_subject.discipline', read_only=True)
room = serializers.CharField(source='para_room.room', read_only=True)
class Meta:
model = Para
fields = (
'discipline', # include this field
'room', # include this field
'para_professor',
'para_number',
'para_day',
'para_group',
'week_type'
)
Post a Comment for "How To Change Serialized JSON Structure Django Rest Framwork"