Python Forum

Full Version: drf ordering by custom field and add ranking in to_representation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
my serizalizer had def to_representation to made some calculation:

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 data
and 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