简体   繁体   中英

Why is dictionary encoding messing up the order of my queryset

I have this 'view'(django):

def preview(request,war_id):
    set = stats.objects.filter(warval=get_object_or_404(war,pk=war_id)).order_by('date')
    for each in set:
        print(each.date)
    f={}
    for each in set:
        date = each.date.strftime('%d %b %Y')
        f[date] = each.views
    print(f)
    return render_to_response('statistics/preview.html',RequestContext(request,{"data":dumps(f)}))

And the output it shows at the command prompt is as follows:

2012-07-01
2012-07-11
2012-07-14
2012-07-19
2012-07-21

{'01 Jul 2012': 34, '11 Jul 2012': 1, '14 Jul 2012': 20, '21 Jul 2012': 6, '19 Jul 2012': 23}

As you see from above output that in dictionary encoding "19 jul 2012" is after "21 jul 2012".Why is that happening?

Dictionaries are unordered. Don't use them if you care about the order of their contents. The collections.OrderedDict class provides an ordered equivalent, but note that this is based on insertion order, not the sort order of the keys.

@BrenBarn's advice about OrderedDict is usually good, but may not be right in this case. It depends on what you are doing in the template. It looks like dumps here is json.dumps , in which case you are likely writing a JSON string to your HTML. In that case, an OrderedDict may not help, because the JSON will be ordered, but then you'll use the JSON in Javascript, which may again produce the values in arbitrary order.

If you care about the order, you should produce a list of lists instead of a dictionary, so that it is treated as an ordered sequence at every stage:

f = []
for each in set:
    date = each.date.strftime('%d %b %Y')
    f.append([date, each.views])
print(f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM