# 更新时间字段,倒序排序
articles = Article.objects.filter(show_status=True).order_by('-time_created')
# 更新时间字段,正序排序
articles = Article.objects.filter(show_status=True).order_by('time_created')
# 更新时间字段,正序排序
articles = Article.objects.order_by('time_created')
也可以使用两个字段进行排序,当 第一个字段值 相等时,再用 第二个 字段值 来排序
articles = Article.objects.order_by('author','-time_created')
models.py
# 主题表/文章表
class Article(models.Model):
title = models.CharField(max_length=128, verbose_name="标题")
content = RichTextUploadingField(verbose_name="内容", config_name='awesome_ckeditor')
author = models.ForeignKey(User, related_name="author_set", verbose_name="作者")
time_created = models.DateTimeField(auto_now_add=True, verbose_name="发表时间")
time_updated = models.DateTimeField(blank=True, null=True, auto_now=True, verbose_name="更新时间")
class Meta:
verbose_name = "文章"
verbose_name_plural = "文章列表"
ordering = ["-time_updated", ]
或 admin.py
class ArticleAdmin(admin.ModelAdmin):
ordering = ["time_updated", ]
每次查询数据库都会默认使用该字段来排序,除非你显示的使用 order_by 语句来排序