1
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'

4
  • 1
    Why would you use bubble sort? TimSort is more efficient, and one normally orders in the database to do this in an efficient way. Commented Aug 17, 2022 at 10:55
  • are you sure your bubble sort is true? Commented Aug 17, 2022 at 10:56
  • Either compare the attributes from the Product instances or define the rich comparison methods in your class. Even better: Don't write a sort method yourself (you could use sorted) or fetch the data from the database in the correct order. Commented Aug 17, 2022 at 10:57
  • yes i want apply bubble sort on it Commented Aug 17, 2022 at 14:41

3 Answers 3

3

You can user order_by():

Product.objects.all().order_by('field_name')
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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')

2 Comments

yeh but i want to apply bubble sort on it
why do you want bubble sort

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.