Malcolm Box 和 Deepak Prakash 的方法可以帮助序列化关系对象,但正如 @eugene 之前所说,它只适用于单个 Alum。对于相册,我们可以这样做:
序列化程序.py
class TrackSerializer(serializers.ModelSerializer):
class Meta:
model = Track
fields = ('order', 'title')
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackSerializer(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
depth=1
api.py
class getAPIView(generics.ListAPIView):
serializer_class=TrackSerializer
filter_backends = (filters.OrderingFilter,)
def get_queryset(self):
queryset=Track.objects.all()
return queryset
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
serializer = self.get_serializer(page, many=True)
data=serializer.data
albums=Album.objects.values_list('album_name').all()
trackObjs=[]
albumObjs=[]
self.categoryKeyList(albums,albumObjs)
if page is not None:
for p in page:
for n,i in enumerate(albums):
if re.search(str(p.alum),str(i)):
albumObjs[n]['track'].append(p)
data={}
data['count']=self.get_paginated_response(self).data['count']
data['next']=self.get_paginated_response(self).data['next']
data['previous']=self.get_paginated_response(self).data['previous']
data['pageNumber'] = self.paginator.page.number
data['countPage'] = self.paginator.page.paginator._count
serializer=ClientsCategorySerializer(categoryObjs,many=True)
data['result']=serializer.data
return Response({'data':data,'success':'1','detail':u'获得客户列表成功'})
def categoryKeyList(self,albums,albumObjs):
for i in albums:
albumObjs={}
albumObjs['album_name']=i[0]
track=[]
albumObj['track']=track
albumObjs.append(albumObj)
然后你可能会得到回应:
{
data[
{
'album_name': 'The Grey Album',
'tracks': [
{'order': 1, 'title': 'Public Service Annoucement'},
{'order': 2, 'title': 'What More Can I Say'},
{'order': 3, 'title': 'Encore'},
...
},
{'album_name': 'The John Album',
'tracks': [
{'order': 1, 'title': 'Public Annoucement'},
{'order': 2, 'title': 'What sd Can I Say'},
{'order': 3, 'title': 'sd'},
...
},
......
}