Mar-24-2021, 09:56 AM
my serizalizer had def to_representation to made some calculation:
And I want to make the output order by the popscore_sum, order it in ViewSet: queryset = Brand.objects.all().order_by('popscore_sum')
So it give an error, I could only use the field from model (i.e. rankings), however rankings was pop so even I order_by('rankings') it will no affect to the result of it.
How could I order it by custom field I added in to_representation? Also after ordering, I would like to add rankings on it (i.e. the ordered sequence no.).
I think this part could handle by using to_representation again and add data['ranking'] on each result, isn't it?
Since data int to_representation is ordered dict, so I tried sorted(data.value()) but it give error '<' not supported between instances of 'str' and 'int'
and tried sorted(data.items()) it doesn't change anything
def to_representation(self, instance): data = super().to_representation(instance) rankings = data.pop('rankings',None) if rankings: popscore_sum = 0 counter = 0 for value in rankings: for key,value in rankings[counter].items(): isFloat = isinstance(value,float) if isFloat: popscore_sum+=value counter+=1 for key,value in rankings[-1].items(): data['createdDate'] = value data['popscore_sum']= popscore_sum/counter return dataand it will pop old serizalizer from it and add new field popscore_sum and 'createdDate'
And I want to make the output order by the popscore_sum, order it in ViewSet: queryset = Brand.objects.all().order_by('popscore_sum')
So it give an error, I could only use the field from model (i.e. rankings), however rankings was pop so even I order_by('rankings') it will no affect to the result of it.
How could I order it by custom field I added in to_representation? Also after ordering, I would like to add rankings on it (i.e. the ordered sequence no.).
I think this part could handle by using to_representation again and add data['ranking'] on each result, isn't it?
Since data int to_representation is ordered dict, so I tried sorted(data.value()) but it give error '<' not supported between instances of 'str' and 'int'
and tried sorted(data.items()) it doesn't change anything