按照entry_date從小到大查詢數據,可以寫成:
Content.objects.order_by('entry_date')
從大到小排序:
Content.objects.order_by('-entry_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 }}在前端獲取到關聯表的數據。