#models.py from django.db import models class Block(models.Model): ... height = models.CharField(max_lenght=256) ...
class Meta:
ordering = ["-height"]
CharField字段存儲的如果是數字,但是又要按照數字排序。
Block.objects.order_by('-height')
由於字符排序和數字排序的方式不同,比如降序排列,height 9999 會在90000之前。
解決辦法:
辦法1.修改Field數據類型
height = models.IntegerField()
辦法2.查詢的時候重新排序
Block.objects.extra(select={'intheight': 'height+0'}).order_by("-intheight")