سؤال

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..

هل كانت مفيدة؟

المحلول

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top