How to query data chains and limit the returned data in the Django framework-Python tutorial

Source: Internet
Author: User
This article mainly introduces the data chain query in the Django framework and the method for limiting the returned data. Django is the most famous popular framework in the Python framework. For more information, see Chain query

We usually need to filter and sort queries at the same time. Therefore, you can simply write this form of "chain:

>>> Publisher.objects.filter(country="U.S.A.").order_by("-name")[
 
  , 
  
   ]
  
 

You should have guessed it. converting to an SQL query is a combination of WHERE and ORDER:

SELECT id, name, address, city, state_province, country, websiteFROM books_publisherWHERE country = 'U.S.A'ORDER BY name DESC;

Restrict returned data

Another common requirement is to retrieve a fixed number of records. Imagine that you have thousands of publishers in your database, but you just want to display the first one. You can use the standard Python list cropping statement:

>>> Publisher.objects.order_by('name')[0]
 

This is equivalent:

SELECT id, name, address, city, state_province, country, websiteFROM books_publisherORDER BY nameLIMIT 1;

Similarly, you can use the range-slicing syntax of Python to retrieve a specific subset of data:

>>> Publisher.objects.order_by('name')[0:2]

In this example, two objects are returned, which is equivalent to the following SQL statement:

SELECT id, name, address, city, state_province, country, websiteFROM books_publisherORDER BY nameOFFSET 0 LIMIT 2;

Note that Python's negative slicing is not supported ):

>>> Publisher.objects.order_by('name')[-1]Traceback (most recent call last): ...AssertionError: Negative indexing is not supported.

Although negative indexes are not supported, we can use other methods. For example, slightly modify the order_by () statement to implement the following:

>>> Publisher.objects.order_by('-name')[0]

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.