tags:

views:

167

answers:

1

In my django project i am using Product.objects.all().order_by('order') in a view, but it dosnt seem to be working properly.

This is its output:

Product Name Sort Evolution 2 Polarity 1 Jumbulaya 3 Kalidascope 4

It should look like this:

Product Name Sort Polarity 1 Evolution 2 Jumbulaya 3 Kalidascope 4


But it dosnt. Any ideas?

My view (for that output):

def debug(request):
    order = Product.objects.all().order_by('order')
    return render_to_response('cms/debug.html', {'order' : order, 'name' : name})

And the view responsible for saving the order field:

def manage_all(request):

if request.method == 'POST':
 PostEntries = len(request.POST)
 x = 1  
 while x < PostEntries:
  p = Product.objects.get(pk=x)
  p.order = int(request.POST.get(str(x),''))
  print "Itr: " + str(x)
  x = x + 1
 p.save()
 print "Product Order saved"  
 return HttpResponse("Saved")

And the model (without the boring bits):

class Product(models.Model):
    name = models.CharField(max_length=100)
    order = models.IntegerField(blank = True, null = True

Here is a 'live' example of the page http://massiveatom.com:8080/debug/ Please note that that is only running on the dev server, so it may not always be up.

I have asked in #django and they didnt seem to know what was going on. One thought was that the database/django was being confused by the sql command it is generating (select * from table where 1 order by 'order'), but i would prefer not to change the order field in the model.

And i know there should be backticks surrounding order in the above sql command, but the syntax parsing thingy kinda hated on it...

Edit: Each object has the correct value, so i dont really know why it isnt sorting it properly.

Edit 2: I dont know what was going on, but it turns out putting p.save() in the loop fixed it all...

+4  A: 

Your saving loop is wrong. You save Product outside of the loop. It should be:

if request.method == 'POST':
    PostEntries = len(request.POST)
    x = 1           
    while x < PostEntries:
            p = Product.objects.get(pk=x)
            p.order = int(request.POST.get(str(x),''))
            print "Itr: " + str(x)
            x = x + 1
            p.save() # NOTE HERE <- saving in loop instead of outside
    print "Product Order saved"             
    return HttpResponse("Saved")
DzinX
Yet author claims that order is correct in DB, strange :)
Dmitry Shevchenko