Django中如何对Product对象进行冒泡排序?解决类型错误问题
问题解决方法
错误原因
你直接用<比较两个Product对象,Python无法识别自定义模型实例的对比逻辑,所以抛出TypeError。必须明确指定对比Product的price字段才行。
方案1:修改冒泡排序逻辑
把冒泡排序里的比较条件改成对比Product的price属性,同时调整排序逻辑实现价格从低到高的升序排列:
def bubble_sort(nts): nts_len = len(nts) for i in range(nts_len): for p in range(nts_len - i - 1): # 前一个商品价格大于后一个时交换,实现升序 if nts[p].price > nts[p+1].price: nts[p], nts[p+1] = nts[p+1], nts[p] return nts def menu(request): products = Product.objects.all() if request.method == "POST": s = request.POST['select'] if s == 'Price: Low to High': list_items = list(products) products = bubble_sort(list_items) # 后续处理products的逻辑...
方案2:用Django ORM自带排序(推荐)
完全没必要自己写冒泡排序,Django的ORM提供了order_by方法,直接让数据库完成排序,性能比内存排序高效得多:
def menu(request): products = Product.objects.all() if request.method == "POST": s = request.POST['select'] if s == 'Price: Low to High': # 按price字段升序排列,加负号可实现降序(如order_by('-price')) products = Product.objects.order_by('price') # 后续处理products的逻辑...
这个方法无需把所有Product对象加载到内存,数据库直接返回排序后的结果,代码更简洁高效。
内容的提问来源于stack exchange,提问作者Anish Kumar Karki
相关产品推荐
相关产品推荐

