When querying a database in Django, how do I return data in reverse order desc?

Source: Internet
Author: User

According to Publish_date from small to large query data, you can write:

    Articles = models. Article.objects.all (). order_by ("Publish_date")


Sort from large to small:

    Articles = models. Article.objects.all (). order_by ("-publish_date")

here are some other sorts of sort

Random Sort:

Content.objects.order_by ('? ')

But Order_by (?) This approach may be expensive and slow, depending on the backend database.

Sort by field in a 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)
# According to the category field code, the Content is sorted, only the foreign key followed by a double underline
Content.objects.order_by (' Category__title ')

# If just follow the foreign key to sort, The default is sorted by the primary key of the associated table
Content.objects.order_by (' category ')
# above equivalent to
Content.objects.order_by (' category__ Code ')

# The double underline returns the result set after the join, and the single underline returns a collection of individual tables
Content.objects.order_by (' Category_title ')

Note: Whether it is a single underline or a double underline, we can use {{Content.category.title}} to get the data of the associated table on the front end.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.