这里是包含商店字典的视图,其中包含以下信息
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>}]
答案 0 :(得分:1)
首先,您应该考虑将变量字典重命名为类似于列表的内容。现在,我假设您要按价格对词典进行排序。如果这是正确的,您可以使用以下内容:
dictionary = sorted(dictionary, key=lambda x:x['price'])
这将按价格的升序排列,使其下降使用
dictionary = sorted(dictionary, key=lambda x:x['price'], reverse=True)