如何在Django中对列表或字典进行排序?

2024-09-29 23:16:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个包含存储字典的视图,其中包含以下信息:

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

然后在表中显示上述数据。这是模板

^{pr2}$

我怎样才能按价格和距离来分类呢?即从低价到高价再从低价到高价

下面是一些示例数据,在应用排序后返回相同的结果-它返回相同的结果。在

[{'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>}]

Tags: storeidsdictionaryobjectsproductfilterpricedistance
1条回答
网友
1楼 · 发布于 2024-09-29 23:16:44

首先,您应该考虑将变量字典重命名为类似于列表的名称。现在,我假设您希望按价格对您的词典进行排序。如果正确,您可以使用以下内容:

dictionary = sorted(dictionary, key=lambda x:x['price'])

这将按价格的升序,使其降序使用

^{pr2}$

相关问题 更多 >

    热门问题