how to change serialized JSON structure django rest framwork

為{幸葍}努か 提交于 2020-06-17 09:31:11

问题


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": "yyyy.yyyy@gmail.com",
            "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": "yyyy.yyyy@gmail.com",
         "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)

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/38142137/how-to-change-serialized-json-structure-django-rest-framwork

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!