1

I'm running a bottle framework and MongoDB. In the dictionary below I need to sort the sub dicts after rank. Mongo don't support sort of the sub docs (unless I sort with $push) and I would prefer to do the sort by "rank" for the media array in python and the template.

an "entry":

{ 
"_id" :"...",
"author" : "...",
"body" : "...",
"date" : ...,
"media" : [
            {
                    "caption" : "Drone",
                    "rank" : "2",
                    "media_link" : "34.jpg"
            },
            {
                    "caption" : "Tea drinker",
                    "rank" : "1",
                    "media_link" : "87.jpg"
            },
            {

                    "caption" : "Daniele",
                    "rank" : "3",
                    "media_link" : "54.jpg"
            }
    ],

}

The template code where I would like to do a sort by rank.

%if ('media' in entry): 
%numMedia = len(entry['media']) 
%else:
%numMedia = 0               
%end


%for i in range(0, numMedia):
<td valign="top">
<img width='200' src='{{entries['media'][i]['media_link']}}'><br>
Media Caption: {{entries['media'][i]['caption']}}<br>
Rank: {{entries['media'][i]['rank']}}</td>
%end

I've tried several different approaches but can't get it to work..

1 Answer 1

1

Hello and welcome TomSjogren, Basically you need to sort the list of sets like this:

media = entry['media']
sorted_media = sorted(media, key=lambda m:m['rank'])

I am not familiar with django, but I think it would be like this then:

%for m in sorted_media:
    <td valign="top">
    <img width='200' src='{{m['media_link']}}'><br>
    Media Caption: {{m['caption']}}<br>
    Rank: {{m['rank']}}</td>
%end
1
  • Worked perfect exactly like you put it. I'm using Bottle not Django but very similar of course. Tnx!!
    – TomSjogren
    Commented Feb 14, 2014 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.