本文介绍了如何更改序列化的JSON结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有可能更改即时识别的JSON结构.currenyly看起来像这样:
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
对象序列化器:
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'
)
对象模型:
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)
推荐答案
您可以在 ParaSerializer
.
这些字段将从提到的 source
中获取值,并将其包含在输出中.
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'
)
这篇关于如何更改序列化的JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!