Reputation: 14521
In my Django project I am using Product.objects.all().order_by('order')
in a view, but it doesn't seem to be working properly.
This is it's output:
Product Name Sort Evolution 2 Polarity 1 Jumbulaya 3 Kalidascope 4It should look like this:
Product Name Sort Polarity 1 Evolution 2 Jumbulaya 3 Kalidascope 4
But it doesn't. 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 didn't 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 back-ticks 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 don't really know why it isn't sorting it properly.
Edit 2: I don't know what was going on, but it turns out putting p.save() in the loop fixed it all...
Upvotes: 1
Views: 683
Reputation: 57874
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")
Upvotes: 5