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] < nts[p 1]:
t = nts[p]
nts[p]= nts[p 1]
nts[p 1] = t
return nts
def menu(request):
products = Product.objects.all()
if request.method == "POST":
s = request.POST['select']
if s == 'Price: Low to High':
element = []
for var in products:
element.append(var)
list_items = list(element)
bb = bubble_sort(list_items)
el = list(bb)
print(el)
pro = Product.objects.filter(id__in=bb)
print(pro)
products = bb
# print(products)
How to retrieve data from database in bubble sort for objects?TypeError: '<' not supported between instances of 'Product' and 'Product'
CodePudding user response:
You can user order_by():
Product.objects.all().order_by('field_name')
CodePudding user response:
your bubble sort looks wrong try this one:
def bubbleSort(lis):
length = len(lis)
for i in range(length):
for j in range(length - i):
a = lis[j]
if a != lis[-1]:
b = lis[j 1]
if a > b:
lis[j] = b
lis[j 1] = a
return lis
and you can sort by django ORM or SQL command like order_by
ASC
or DESC
CodePudding user response:
You use order_by()
# if you want products in ascending order by field_name
ordered_products = Product.objects.order_by('field_name')
# if your want products in descending order by field_name
ordered_products = Product.objects.order_by('-field_name')