Taras_G
Taras_G

Reputation: 65

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"
    },
    "para_room": {
      "room": "210"
    },
    "para_professor": {
        "user": {
            "username": "yyyy",
            "email": "[email protected]",
            "first_name": "yyyy",
            "last_name": "yyy"
         },
        "middle_name": "xxxxxx"
     },

}

what is the best way to change it to this:

  {
    "discipline": "MATAN",
    "room": "210",
    "para_professor": {
        "username": "yyyy",
         "email": "[email protected]",
         "first_name": "yyyy",
         "last_name": "yyy"
         "middle_name": "xxxx"
         },
    }

UPDATE: Adding serializer and model upon to the request in comments

Object Serializer:

class ParaSerializer(serializers.ModelSerializer):
    para_subject = DisciplineSerializer()
    para_room = RoomSerializer()
    para_professor = ProfessorProfileForScheduleSerializer(read_only=True)
    para_number = ParaTimeSerializer()
    para_day = WorkingDaySerializer()
    # para_group = StudentGroupSerializer()

    class Meta:
        model = Para
        fields = (
            'para_subject',
            'para_room',
            'para_professor',
            'para_number',
            'para_day',
            'para_group',
            'week_type'
        )

Object Model:

class Para(models.Model):

    class Meta(object):
        verbose_name = u"Class"
        verbose_name_plural = u"Classes"

    para_subject = models.ForeignKey(
        'Disciplines',
        blank=True,
        null=True,
        verbose_name=u"Discipline"
    )
    para_room = models.ForeignKey(
        'Rooms',
        blank=True,
        null=True,
        verbose_name=u"Room"
    )
    para_professor = models.ForeignKey(
        'students.ProfileModel',
        blank=True,
        null=True,
        verbose_name=u"Professor"
    )
    para_number = models.ForeignKey(
        'ParaTime',
        blank=True,
        null=True,
        verbose_name=u"Class Starts/Ends"
    )
    para_day = models.ForeignKey(
        WorkingDay,
        blank=True,
        null=True,
        verbose_name=u"Working day")

    para_group = models.ForeignKey(
        'StudentGroupModel',
        blank=True,
        null=True,
        verbose_name=u"Student Group"
    )
    week_type = models.BooleanField(
        default=True,
        verbose_name=u"Is week even"
    )

    def __unicode__(self):
        return u"%s %s" % (self.para_subject, self.para_room)

Upvotes: 1

Views: 1119

Answers (2)

Rahul Gupta
Rahul Gupta

Reputation: 47906

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'
        )

Upvotes: 2

Florian Reiner
Florian Reiner

Reputation: 43

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
            }
        }

Upvotes: 3

Related Questions