[英]How to sort a list or dictionary in django?
這是包含商店字典的視圖,其中包含以下信息:
dictionary = []
for store in stores:
store = Store.objects.get(StoreName=store)
ids = StoreProduct.objects.filter(product=productobj , store__StoreName=store).values_list('store__id' , flat=True).distinct()
price = StoreProduct.objects.filter(product=productobj , store__StoreName=store).values_list('price' , flat=True).first()
distance = StoreLocation.objects.user_store_distance(user_lat , user_long , store.storelocation.latitude , store.storelocation.longitude)
dictionary.append({ 'store' : store , 'ids' : ids , 'price' : price , 'latitude' : store.storelocation.latitude ,
'longitude':store.storelocation.longitude , 'distance':distance})
print dictionary
dictionary = sorted(dictionary, key=lambda x:x['distance'])
print dictionary
然后在表中顯示上述數據。這是模板
<table class="wrapper storetable" onload="showmore()">
<tr class="text-center" id="tablehead"><td style="width: 70px"></td><td>Store Name</td><td>Price</td><td>Distance</td>
<td>Sort<br><select id="sort_table"><option>Relevance</option><option>Distance</option><option>Price</option></select></td></tr>
{% for item in ProductStores %}
<tr class="text-center">
<td style="width: 70px; font-size:20px"><a href="#" data-lat="{{item.latitude}},{{item.longitude}}" data-toggle="modal" data-target="#myMapModal"><span class="glyphicon glyphicon-map-marker" aria-hidden="true"></span></a></td>
<td>
{{ item.store }} <br> {{ storeproduct.store.MallName }}
</td>
<td> Rs. {{ item.price }}</td>
<td>{{ item.distance}} Kms.</td>
<td>
<button class="button" type="Submit" id="addtocart" onclick="getCart(event,{{ product.id }} , {{ minId }})">ADD TO BAG</button>
</td>
</tr>
{% endfor %}
</table>
如何按價格和距離對以上內容進行排序? 即從低到高的價格,然后從低到高的距離
這是一些樣本數據,在應用排序后返回相同的結果。
[{'distance': '100.79', 'price': 2100L, 'ids': [1L], 'longitude': u'77.2090', 'latitude': u'28.6139', 'store': <Store: DOROTHY>}, {'distance': '91.71', 'price': 2100L, 'ids': [4L], 'lo
ngitude': u'77.29275380000001', 'latitude': u'28.63642', 'store': <Store: Dorothy Perkins PV>}]
[{'distance': '100.79', 'price': 2100L, 'ids': [1L], 'longitude': u'77.2090', 'latitude': u'28.6139', 'store': <Store: DOROTHY>}, {'distance': '91.71', 'price': 2100L, 'ids': [4L], 'lo
ngitude': u'77.29275380000001', 'latitude': u'28.63642', 'store': <Store: Dorothy Perkins PV>}]
首先,您應該考慮將變量字典重命名為類似於列表的名稱。 現在,假設您要按價格對字典進行排序。 如果正確,則可以使用以下命令:
dictionary = sorted(dictionary, key=lambda x:x['price'])
這將按價格升序使用
dictionary = sorted(dictionary, key=lambda x:x['price'], reverse=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.