Khóa học miễn phí Returning List and Scalars nhận dự án làm có lương

Returning List and Scalars



There are a number of methods of Query object that immediately issue SQL and return a value containing loaded database results.

Here’s a brief rundown of returning list and scalars −

all()

It returns a list. Given below is the line of code for all() function.

session.query(Customers).all()

Python console displays following SQL expression emitted −

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers

first()

It applies a limit of one and returns the first result as a scalar.

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
LIMIT ? OFFSET ?

The bound parameters for LIMIT is 1 and for OFFSET is 0.

one()

This command fully fetches all rows, and if there is not exactly one object identity or composite row present in the result, it raises an error.

session.query(Customers).one()

With multiple rows found −

MultipleResultsFound: Multiple rows were found for one()

With no rows found −

NoResultFound: No row was found for one()

The one() method is useful for systems that expect to handle “no items found” versus “multiple items found” differently.

scalar()

It invokes the one() method, and upon success returns the first column of the row as follows −

session.query(Customers).filter(Customers.id == 3).scalar()

This generates following SQL statement −

SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE customers.id = ?

Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc