Querying data according to entry_date from small to large can be written as:
Content.objects.order_by('entry_date')
Sort from large to small:
Content.objects.order_by('-entry_date')
The following introduces other types of sorting
Random sorting:
Content.objects.order_by('?')
But the order_by(?) method may be expensive and slow, depending on the backend database.
Sort by fields of the relational table
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: Whether it is a single underscore or a double underscore, we can use {{ content.category.title }} to obtain the data of the relational table on the front end.
【Related Tutorial Recommendations】
1. "Python Free Video Tutorial"
2. Basic Introduction to Python Tutorial
3. Application of Python in Data Science
The above is the detailed content of Introducing various types of sorting when Django queries the database. For more information, please follow other related articles on the PHP Chinese website!