80.常用的返回QuerySet对象的方法使用详解:order_by

时间:2023-03-09 17:37:47
80.常用的返回QuerySet对象的方法使用详解:order_by

order_by: 将模型生成的表按照某个字段进行排序,默认情况下,按照升序的顺序排序,如果想要按照降序的顺序排序可以在字段的前面加一个“-”,加一个负号就可以进行反转。

models.py文件中示例代码如下:
from django.db import models

class Category(models.Model):
name = models.CharField(max_length=100)
rating = models.FloatField(null=True) class Meta:
db_table = 'category' class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True)
create_time = models.DateTimeField(auto_now_add=True, null=True) def __str__(self):
return "<(Article: id: %s,title: %s, content: %s)>" % (self.id, self.title, self.content) class Meta:
db_table = 'article'
mysql数据库表中article表和category表中的数据如下所示:

80.常用的返回QuerySet对象的方法使用详解:order_by

80.常用的返回QuerySet对象的方法使用详解:order_by

1.order_by: 传递一个字段名,对表中的数据进行排序,默认情况对所有的数据做升序的排序操作。示例代码如下:
from django.db.models import F, Q
from django.db improt connection
from .models import Article, Category
from django.http import HttpResponse def index(request):
articles = Article.objects.order_by('create_time')
for article in articles:
print("%s, %s, %s" % (article.id, article.title, article.create_time))
print(connection.queries)
return HttpResponse("success!")
2. order_by: 传递一个字段名,对表中所有数据做降序操作,可以通过在字段名前面添加一个负号来解决。示例代码如下:
from django.db.models import F, Q
from django.db improt connection
from .models import Article, Category
from django.http import HttpResponse def index(request):
articles = Article.objects.order_by('-create_time')
for article in articles:
print("%s, %s, %s" % (article.id, article.title, article.create_time))
print(connection.queries)
return HttpResponse("success!")
3. order_by:传递多个参数,首先按照category_id从小到大进行排序,之后按照create_time从大到小排序。示例代码如下:
from django.db.models import F, Q
from django.db improt connection
from .models import Article, Category
from django.http import HttpResponse def index6(request):
# 将article表首先按category_id进行从小到大排序,之后在按create_time从大到小排序
articles = Article.objects.order_by('category', '-create_time')
for article in articles:
# 遍历每一个对象
print("%s, %s, %s" % (article.id, article.category, article.create_time))
# 查看原生sql语句
print(connection.queries)
return HttpResponse("success!")
注意:如果需要按照多个字段进行排序,不能使用多个order_by()语句链式调用实现,如果使用多个order_by语句,最后的排序结果是按最后一个order_by()语句传递的字段名进行排序的结果。
def index6(request):
# 将article表首先按category_id进行从小到大排序,之后在按create_time从大到小排序
# 不能使用链式的多个order_by()语句。这样的结果只会使用最后一个order_by语句的条件进行排序
articles = Article.objects.order_by('category').order_by('create_time')
for article in articles:
print("%s, %s, %s" % (article.id, article.title, article.create_time))
print(connection.queries)
return HttpResponse("success!")
4. 同样,在排序的时候可以在模型的定义的时候指定Meta类,给Meta类中的ordering属性传递一个列表,数据库表中的字段的顺序就是表中的字段排序的顺序
5.通过外键的关系映射出的关联表之间的排序。比如,首先将article表中的文章按创建的时间从大到小排序,之后按照文章的分类的评分从小到大进行排序。示例代码如下:
def index6(request):
# 关联表之间的排序
# 首先将article表中的文章按创建的时间从大到小排序,之后按照文章的分类的评分从小到大进行排序
articles = Article.objects.order_by('-create_time', 'category__rating')
for article in articles:
print("%s, %s, %s" % (article.id, article.category.rating, article.create_time))
print(connection.queries)
return HttpResponse("success")
查询结果为:

2, 3.4, 2020-02-05 03:04:59.860556+00:00

1, 3.6, 2020-02-05 03:04:59.860556+00:00

4, 3.6, 2020-02-05 03:04:59.860556+00:00

3, 4.8, 2020-02-05 03:03:30.860556+00:00

原生sql语句:SELECT article.id, article.title, article.content, article.category_id, article.create_time FROM article LEFT OUTER JOIN category ON (article.category_id = category.id) ORDER BY article.create_time DESC, category.rating ASC

6.将分类中图书的数量从多到少进行排序,示例代码如下:
from django.db import Count

def index6(request):
# 将分类按分类中的图书的数量从多到少进行排序
# 首先统计出每个分类中图书的数量,并且添加一个图书数量的字段
categories = Category.objects.annotate(article_nums=Count('article__category__id')).order_by('-article_nums')
for category in categories:
print("%s/%s/%s" % (category.id, category.name, category.article_nums))
print(categories.query)
return HttpResponse("success!")
打印出结果如下所示:

1/最新文章/2

2/最热文章/1

3/高评分文章/1

django底层执行的sql语句为: SELECT category.id, category.name, category.rating, COUNT(article.category_id) AS article_nums FROM category LEFT OUTER JOIN article ON (category.id = article.category_id) GROUP BY category.id ORDER BY article_nums DESC