按照entry_date从小到大查询数据,可以写成:
1 | Content.objects.order_by( 'entry_date' ) |
从大到小排序:
1 | Content.objects.order_by( '-entry_date' ) |
下面介绍其他种类的排序
随机排序:
1 | Content.objects.order_by( '?' ) |
但是order_by(?)这种方式也许expensive并且slow,这取决于后端数据库。
按照关系表的字段排序
1 2 3 4 5 6 7 | class Category(Base): code = models.CharField(primary_key = True ,max_length = 100 ) title = models.CharField(max_length = 255 ) class Content(Base): title = models.CharField(max_length = 255 ) description = models.TextField() category = models.ForeignKey(Category, on_delete = models.CASCADE) |
1 2 3 4 5 6 7 8 | # 按照Category的字段code,对Content进行排序,只需要外键后加双下划线 Content.objects.order_by( 'category__title' ) # 如果只是按照外键来排序,会默认按照关联的表的主键排序 Content.objects.order_by( 'category' ) # 上面等价于 Content.objects.order_by( 'category__code' ) # 双下划线返回的是join后的结果集,而单下划线返回的是单个表的集合 Content.objects.order_by( 'category_title' ) |
Note: 无论是单下划线还是双下划线,我们都可用{{ content.category.title }}在前端获取到关联表的数据。
转自:http://www.php.cn/python-tutorials-362108.html