您的位置:首页 > 数据库

在Django里查询数据库时,如何按照desc倒序返回数据?

2017-09-06 11:24 246 查看
按照 publish_date 从小到大查询数据,可以写成:

articles = models.Article.objects.all().order_by("publish_date")


从大到小排序:

articles = models.Article.objects.all().order_by("-publish_date")


 

下面介绍其他种类的排序

随机排序:

Content.objects.order_by('?')


但是order_by(?)这种方式也许expensive并且slow,这取决于后端数据库。

按照关系表的字段排序

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)


# 按照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 }}在前端获取到关联表的数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: