• django对数据查询结果进行排序的方法


    在你的 Django 应用中,你或许希望根据某字段的值对检索结果排序,比如说,按字母顺序。 那么,使用 order_by() 这个方法就可以搞定了。

    1
    2
    >>> Publisher.objects.order_by("name")
    [<Publisher: Apress>, <Publisher: O'Reilly>]

    跟以前的 all() 例子差不多,SQL语句里多了指定排序的部分:

    1
    2
    3
    SELECT id, name, address, city, state_province, country, website
    FROM books_publisher
    ORDER BY name;

    我们可以对任意字段进行排序:

    1
    2
    3
    4
    5
    >>> Publisher.objects.order_by("address")
    [<Publisher: O'Reilly>, <Publisher: Apress>]
     
    >>> Publisher.objects.order_by("state_province")
    [<Publisher: Apress>, <Publisher: O'Reilly>]

    如果需要以多个字段为标准进行排序(第二个字段会在第一个字段的值相同的情况下被使用到),使用多个参数就可以了,如下:

    1
    2
    >>> Publisher.objects.order_by("state_province", "address")
     [<Publisher: Apress>, <Publisher: O'Reilly>]

    我们还可以指定逆向排序,在前面加一个减号 - 前缀:

    1
    2
    >>> Publisher.objects.order_by("-name")
    [<Publisher: O'Reilly>, <Publisher: Apress>]

    尽管很灵活,但是每次都要用 order_by() 显得有点啰嗦。 大多数时间你通常只会对某些 字段进行排序。 在这种情况下,Django让你可以指定模型的缺省排序方式:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Publisher(models.Model):
      name = models.CharField(max_length=30)
      address = models.CharField(max_length=50)
      city = models.CharField(max_length=60)
      state_province = models.CharField(max_length=30)
      country = models.CharField(max_length=50)
      website = models.URLField()
     
      def __unicode__(self):
        return self.name
     
      **class Meta:**
        **ordering = ['name']**

    现在,让我们来接触一个新的概念。 class Meta,内嵌于 Publisher 这个类的定义中(如果 class Publisher 是顶格的,那么 class Meta 在它之下要缩进4个空格--按 Python 的传统 )。你可以在任意一个 模型 类中使用 Meta 类,来设置一些与特定模型相关的选项。 在 附录B 中有 Meta 中所有可选项的完整参考,现在,我们关注 ordering 这个选项就够了。 如果你设置了这个选项,那么除非你检索时特意额外地使用了 order_by(),否则,当你使用 Django 的数据库 API 去检索时,Publisher对象的相关返回值默认地都会按 name 字段排序。

  • 相关阅读:
    输入一个正整数n (1<n<=10),生成 1个 n*n 方阵 求出对角线之和
    关闭ubuntu讨厌的内部错误提示
    ubuntu14.04通过 gvm 安装 go语言开发环境
    codeblocks 控制台输出乱码
    opensuse13.2安装 sass和compass
    执行npm publish 报错:403 Forbidden
    执行npm publish 报错:401 Unauthorized
    使用form表单提交请求如何获取后台返回的数据?
    vscode学习(三)之如何修改打开终端的默认shell
    Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” a...
  • 原文地址:https://www.cnblogs.com/yingqml/p/6200558.html
Copyright © 2020-2023  润新知