.order_by()无法正常工作/我期望如何
时间:2020-03-06 14:58:11 来源:igfitidea点击:
在我的Django项目中,我正在视图中使用Product.objects.all()。order_by('order')
,但它似乎无法正常工作。
这是它的输出:
产品名称分类演变2极性1巨型伞3 Kalidascope 4
它看起来应该像这样:
产品名称排序极性1演化2巨型伞3 Kalidascope 4
但事实并非如此。有任何想法吗?
我的看法(针对该输出):
def debug(request): order = Product.objects.all().order_by('order') return render_to_response('cms/debug.html', {'order' : order, 'name' : name})
和负责保存订单字段的视图:
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")
和模型(无聊的地方):
class Product(models.Model): name = models.CharField(max_length=100) order = models.IntegerField(blank = True, null = True
这是页面http://massiveatom.com:8080/debug/的"实时"示例,请注意,该示例仅在开发服务器上运行,因此可能并不总是启动。
我在#django中问过,他们似乎不知道发生了什么。一种想法是数据库/ Django被它所生成的SQL命令所迷惑(从表中选择" *",其中" order"表示1个订单),但是我不想更改模型中的order字段。
而且我知道上述SQL命令中应该有反引号左右的顺序,但是语法分析对此有点讨厌...
编辑:每个对象都有正确的值,所以我真的不知道为什么它不能正确排序。
编辑2:我不知道发生了什么,但事实证明,将p.save()放入循环中修复了所有问题...
解决方案
保存循环是错误的。我们将产品保存在循环之外。它应该是:
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")