我有一个端点,可以给出这样的响应:
{
"theatershowtime" : [
{
"movietime" : "2014-11-23T02:40:00Z",
"mvtype" : "3D"
},
{
"movietime" : "2014-11-23T05:40:00Z",
"mvtype" : "3D"
},
{
"movietime" : "2014-11-23T03:40:00Z",
"mvtype" : "IMAX"
},
]
}
这是我的serializes.py:
class TheaterSerializer(serializers.ModelSerializer):
theatershowtime = MovieShowtimeSerializer(many=True, read_only=True, source='theater')
class Meta:
model = MovieTheater
fields = ('theatershowtime', )
class MovieShowtimeSerializer(serializers.ModelSerializer):
class Meta:
model = MovieShowtime
fields = ( 'movietime', 'mvtype', )
我学会了一种如何显示的方法:
"Times": [
"2014-11-23T02:40:00Z",
"2014-11-23T05:40:00Z",
"2014-11-23T03:40:00Z",
]
它使用了这个serializes.py:
class TheaterSerializer(serializers.ModelSerializer):
Times = serializers.SerializerMethodField('get_movietimes')
def get_movietimes(self, obj):
movietimes = []
for i in obj.theater.all():
movietimes.append(i.movietime)
return movietimes
class Meta:
model = MovieTheater
fields = ('Times', )
但我希望得到这样的答复:
theatershowtime: {
Times: {
3D: [
"2014-11-23T02:40:00Z",
"2014-11-23T05:40:00Z",
],
IMAX: [
"2014-11-23T03:40:00Z",
]
}
},
请帮帮我!非常感谢!!!
答案 0 :(得分:0)
尝试使用此代码段:
...
def get_movietimes(self, obj):
movietimes = {}
for i in obj.theater.all():
if i.mvtype not in movietimes:
movietimes[i.mvtype] = []
movietimes[i.mvtype].append(i.movietime)
return movietimes
...