简体   繁体   English

为什么字典编码会弄乱我的查询集的顺序

[英]Why is dictionary encoding messing up the order of my queryset

I have this 'view'(django): 我有这个“观点”(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? 从上面的输出中可以看到,词典编码中的“ 2012年7月19日”在“ 2012年7月21日”之后。为什么会这样?

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. collections.OrderedDict类提供有序等效项,但是请注意,这是基于插入顺序而不是键的排序顺序。

@BrenBarn's advice about OrderedDict is usually good, but may not be right in this case. @BrenBarn关于OrderedDict的建议通常是好的,但在这种情况下可能不正确。 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. 看起来这里的dumpsjson.dumps ,在这种情况下,您可能会向HTML编写JSON字符串。 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. 在这种情况下,OrderedDict可能无济于事,因为将对JSON进行排序,但是您将在Javascript中使用JSON,这可能会再次以任意顺序生成值。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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