Introducing various types of sorting when Django queries the database

伊谢尔伦
Release: 2018-05-18 16:53:10
Original
4284 people have browsed it

Querying data according to entry_date from small to large can be written as:

Content.objects.order_by('entry_date')
Copy after login

Sort from large to small:

Content.objects.order_by('-entry_date')
Copy after login

The following introduces other types of sorting

Random sorting:

Content.objects.order_by('?')
Copy after login

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)
Copy after login
# 按照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')
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template