Python Forum
drf ordering by custom field and add ranking in to_representation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
drf ordering by custom field and add ranking in to_representation
#1
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
Reply


Messages In This Thread
drf ordering by custom field and add ranking in to_representation - by tomfong521 - Mar-24-2021, 09:56 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Use ranking function for different lists klatlap 6 2,104 Feb-15-2022, 11:31 PM
Last Post: klatlap
  Help with Matplotlib and ordering the axis theliberalguy97 3 8,449 Dec-12-2020, 08:06 PM
Last Post: deanhystad
  What are these ordering code doing coltson 1 1,841 Nov-03-2020, 05:07 AM
Last Post: deanhystad
  Bug ? when dataclass field name == field type Cyril 0 1,607 Oct-22-2020, 03:26 AM
Last Post: Cyril
  Help with plot, how to show ranking with boxes icebelt 1 2,528 Jan-25-2019, 10:00 AM
Last Post: Larz60+
  Ordering a list of dict giu88 2 2,814 Nov-05-2018, 02:12 PM
Last Post: giu88

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020