Author: alien

  • Khóa học miễn phí Eager Loading nhận dự án làm có lương

    SQLAlchemy ORM – Eager Loading



    Eager load reduces the number of queries. SQLAlchemy offers eager loading functions invoked via query options which give additional instructions to the Query. These options determine how to load various attributes via the Query.options() method.

    Subquery Load

    We want that Customer.invoices should load eagerly. The orm.subqueryload() option gives a second SELECT statement that fully loads the collections associated with the results just loaded. The name “subquery” causes the SELECT statement to be constructed directly via the Query re-used and embedded as a subquery into a SELECT against the related table.

    from sqlalchemy.orm import subqueryload
    c1 = session.query(Customer).options(subqueryload(Customer.invoices)).filter_by(name = ''Govind Pant'').one()
    

    This results in the following two SQL expressions −

    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.name = ?
    (''Govind Pant'',)
    
    SELECT invoices.id
    AS invoices_id, invoices.custid
    AS invoices_custid, invoices.invno
    AS invoices_invno, invoices.amount
    AS invoices_amount, anon_1.customers_id
    AS anon_1_customers_id
    FROM (
       SELECT customers.id
       AS customers_id
       FROM customers
       WHERE customers.name = ?)
    
    AS anon_1
    JOIN invoices
    ON anon_1.customers_id = invoices.custid
    ORDER BY anon_1.customers_id, invoices.id 2018-06-25 18:24:47,479
    INFO sqlalchemy.engine.base.Engine (''Govind Pant'',)
    

    To access the data from two tables, we can use the below program −

    print (c1.name, c1.address, c1.email)
    
    for x in c1.invoices:
       print ("Invoice no : {}, Amount : {}".format(x.invno, x.amount))
    

    The output of the above program is as follows −

    Govind Pant Gulmandi Aurangabad gpant@gmail.com
    Invoice no : 3, Amount : 10000
    Invoice no : 4, Amount : 5000
    

    Joined Load

    The other function is called orm.joinedload(). This emits a LEFT OUTER JOIN. Lead object as well as the related object or collection is loaded in one step.

    from sqlalchemy.orm import joinedload
    c1 = session.query(Customer).options(joinedload(Customer.invoices)).filter_by(name=''Govind Pant'').one()
    

    This emits following expression giving same output as above −

    SELECT customers.id
    AS customers_id, customers.name
    AS customers_name, customers.address
    AS customers_address, customers.email
    AS customers_email, invoices_1.id
    AS invoices_1_id, invoices_1.custid
    AS invoices_1_custid, invoices_1.invno
    AS invoices_1_invno, invoices_1.amount
    AS invoices_1_amount
    
    FROM customers
    LEFT OUTER JOIN invoices
    AS invoices_1
    ON customers.id = invoices_1.custid
    
    WHERE customers.name = ? ORDER BY invoices_1.id
    (''Govind Pant'',)
    

    The OUTER JOIN resulted in two rows, but it gives one instance of Customer back. This is because Query applies a “uniquing” strategy, based on object identity, to the returned entities. Joined eager loading can be applied without affecting the query results.

    The subqueryload() is more appropriate for loading related collections while joinedload() is better suited for many-to-one relationship.


    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

  • Khóa học miễn phí Common Relationship Operators nhận dự án làm có lương

    Common Relationship Operators



    In this chapter, we will discuss about the operators which build on relationships.

    __eq__()

    The above operator is a many-to-one “equals” comparison. The line of code for this operator is as shown below −

    s = session.query(Customer).filter(Invoice.invno.__eq__(12))
    

    The equivalent SQL query for the above line of code is −

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

    __ne__()

    This operator is a many-to-one “not equals” comparison. The line of code for this operator is as shown below −

    s = session.query(Customer).filter(Invoice.custid.__ne__(2))
    

    The equivalent SQL query for the above line of code is given below −

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

    contains()

    This operator is used for one-to-many collections and given below is the code for contains() −

    s = session.query(Invoice).filter(Invoice.invno.contains([3,4,5]))
    

    The equivalent SQL query for the above line of code is −

    SELECT invoices.id
    AS invoices_id, invoices.custid
    AS invoices_custid, invoices.invno
    AS invoices_invno, invoices.amount
    AS invoices_amount
    FROM invoices
    WHERE (invoices.invno LIKE ''%'' + ? || ''%'')
    

    any()

    any() operator is used for collections as shown below −

    s = session.query(Customer).filter(Customer.invoices.any(Invoice.invno==11))
    

    The equivalent SQL query for the above line of code is shown below −

    SELECT customers.id
    AS customers_id, customers.name
    AS customers_name, customers.address
    AS customers_address, customers.email
    AS customers_email
    FROM customers
    WHERE EXISTS (
       SELECT 1
       FROM invoices
       WHERE customers.id = invoices.custid
       AND invoices.invno = ?)
    

    has()

    This operator is used for scalar references as follows −

    s = session.query(Invoice).filter(Invoice.customer.has(name = ''Arjun Pandit''))
    

    The equivalent SQL query for the above line of code is −

    SELECT invoices.id
    AS invoices_id, invoices.custid
    AS invoices_custid, invoices.invno
    AS invoices_invno, invoices.amount
    AS invoices_amount
    FROM invoices
    WHERE EXISTS (
       SELECT 1
       FROM customers
       WHERE customers.id = invoices.custid
       AND customers.name = ?)
    

    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

  • Khóa học miễn phí Working with Joins nhận dự án làm có lương

    SQLAlchemy ORM – Working with Joins



    Now that we have two tables, we will see how to create queries on both tables at the same time. To construct a simple implicit join between Customer and Invoice, we can use Query.filter() to equate their related columns together. Below, we load the Customer and Invoice entities at once using this method −

    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind = engine)
    session = Session()
    
    for c, i in session.query(Customer, Invoice).filter(Customer.id == Invoice.custid).all():
       print ("ID: {} Name: {} Invoice No: {} Amount: {}".format(c.id,c.name, i.invno, i.amount))
    

    The SQL expression emitted by SQLAlchemy is as follows −

    SELECT customers.id
    AS customers_id, customers.name
    AS customers_name, customers.address
    AS customers_address, customers.email
    AS customers_email, invoices.id
    AS invoices_id, invoices.custid
    AS invoices_custid, invoices.invno
    AS invoices_invno, invoices.amount
    AS invoices_amount
    FROM customers, invoices
    WHERE customers.id = invoices.custid
    

    And the result of the above lines of code is as follows −

    ID: 2 Name: Gopal Krishna Invoice No: 10 Amount: 15000
    ID: 2 Name: Gopal Krishna Invoice No: 14 Amount: 3850
    ID: 3 Name: Govind Pant Invoice No: 3 Amount: 10000
    ID: 3 Name: Govind Pant Invoice No: 4 Amount: 5000
    ID: 4 Name: Govind Kala Invoice No: 7 Amount: 12000
    ID: 4 Name: Govind Kala Invoice No: 8 Amount: 8500
    ID: 5 Name: Abdul Rahman Invoice No: 9 Amount: 15000
    ID: 5 Name: Abdul Rahman Invoice No: 11 Amount: 6000
    

    The actual SQL JOIN syntax is easily achieved using the Query.join() method as follows −

    session.query(Customer).join(Invoice).filter(Invoice.amount == 8500).all()
    

    The SQL expression for join will be displayed on the console −

    SELECT customers.id
    AS customers_id, customers.name
    AS customers_name, customers.address
    AS customers_address, customers.email
    AS customers_email
    FROM customers JOIN invoices ON customers.id = invoices.custid
    WHERE invoices.amount = ?
    

    We can iterate through the result using for loop −

    result = session.query(Customer).join(Invoice).filter(Invoice.amount == 8500)
    for row in result:
       for inv in row.invoices:
          print (row.id, row.name, inv.invno, inv.amount)
    

    With 8500 as the bind parameter, following output is displayed −

    4 Govind Kala 8 8500
    

    Query.join() knows how to join between these tables because there’s only one foreign key between them. If there were no foreign keys, or more foreign keys, Query.join() works better when one of the following forms are used −

    query.join(Invoice, id == Address.custid) explicit condition
    query.join(Customer.invoices) specify relationship from left to right
    query.join(Invoice, Customer.invoices) same, with explicit target
    query.join(”invoices”) same, using a string

    Similarly outerjoin() function is available to achieve left outer join.

    query.outerjoin(Customer.invoices)
    

    The subquery() method produces a SQL expression representing SELECT statement embedded within an alias.

    from sqlalchemy.sql import func
    
    stmt = session.query(
       Invoice.custid, func.count(''*'').label(''invoice_count'')
    ).group_by(Invoice.custid).subquery()
    

    The stmt object will contain a SQL statement as below −

    SELECT invoices.custid, count(:count_1) AS invoice_count FROM invoices GROUP BY invoices.custid
    

    Once we have our statement, it behaves like a Table construct. The columns on the statement are accessible through an attribute called c as shown in the below code −

    for u, count in session.query(Customer, stmt.c.invoice_count).outerjoin(stmt, Customer.id == stmt.c.custid).order_by(Customer.id):
       print(u.name, count)
    

    The above for loop displays name-wise count of invoices as follows −

    Arjun Pandit None
    Gopal Krishna 2
    Govind Pant 2
    Govind Kala 2
    Abdul Rahman 2
    

    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

  • Khóa học miễn phí Working with Related Objects nhận dự án làm có lương

    Working with Related Objects



    In this chapter, we will focus on the related objects in SQLAlchemy ORM.

    Now when we create a Customer object, a blank invoice collection will be present in the form of Python List.

    c1 = Customer(name = "Gopal Krishna", address = "Bank Street Hydarebad", email = "gk@gmail.com")
    

    The invoices attribute of c1.invoices will be an empty list. We can assign items in the list as −

    c1.invoices = [Invoice(invno = 10, amount = 15000), Invoice(invno = 14, amount = 3850)]
    

    Let us commit this object to the database using Session object as follows −

    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind = engine)
    session = Session()
    session.add(c1)
    session.commit()
    

    This will automatically generate INSERT queries for customers and invoices tables −

    INSERT INTO customers (name, address, email) VALUES (?, ?, ?)
    (''Gopal Krishna'', ''Bank Street Hydarebad'', ''gk@gmail.com'')
    INSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?)
    (2, 10, 15000)
    INSERT INTO invoices (custid, invno, amount) VALUES (?, ?, ?)
    (2, 14, 3850)
    

    Let us now look at contents of customers table and invoices table in the table view of SQLiteStudio −

    Customers Table View

    Invoices Table

    You can construct Customer object by providing mapped attribute of invoices in the constructor itself by using the below command −

    c2 = [
       Customer(
          name = "Govind Pant",
          address = "Gulmandi Aurangabad",
          email = "gpant@gmail.com",
          invoices = [Invoice(invno = 3, amount = 10000),
          Invoice(invno = 4, amount = 5000)]
       )
    ]
    

    Or a list of objects to be added using add_all() function of session object as shown below −

    rows = [
       Customer(
          name = "Govind Kala",
          address = "Gulmandi Aurangabad",
          email = "kala@gmail.com",
          invoices = [Invoice(invno = 7, amount = 12000), Invoice(invno = 8, amount = 18500)]),
    
       Customer(
          name = "Abdul Rahman",
          address = "Rohtak",
          email = "abdulr@gmail.com",
          invoices = [Invoice(invno = 9, amount = 15000),
          Invoice(invno = 11, amount = 6000)
       ])
    ]
    
    session.add_all(rows)
    session.commit()
    

    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

  • Khóa học miễn phí Building Relationship nhận dự án làm có lương

    SQLAlchemy ORM – Building Relationship



    This session describes creation of another table which is related to already existing one in our database. The customers table contains master data of customers. We now need to create invoices table which may have any number of invoices belonging to a customer. This is a case of one to many relationships.

    Using declarative, we define this table along with its mapped class, Invoices as given below −

    from sqlalchemy import create_engine, ForeignKey, Column, Integer, String
    engine = create_engine(''sqlite:///sales.db'', echo = True)
    from sqlalchemy.ext.declarative import declarative_base
    Base = declarative_base()
    from sqlalchemy.orm import relationship
    
    class Customer(Base):
       __tablename__ = ''customers''
    
       id = Column(Integer, primary_key = True)
       name = Column(String)
       address = Column(String)
       email = Column(String)
    
    class Invoice(Base):
       __tablename__ = ''invoices''
    
       id = Column(Integer, primary_key = True)
       custid = Column(Integer, ForeignKey(''customers.id''))
       invno = Column(Integer)
       amount = Column(Integer)
       customer = relationship("Customer", back_populates = "invoices")
    
    Customer.invoices = relationship("Invoice", order_by = Invoice.id, back_populates = "customer")
    Base.metadata.create_all(engine)
    

    This will send a CREATE TABLE query to SQLite engine as below −

    CREATE TABLE invoices (
       id INTEGER NOT NULL,
       custid INTEGER,
       invno INTEGER,
       amount INTEGER,
       PRIMARY KEY (id),
       FOREIGN KEY(custid) REFERENCES customers (id)
    )
    

    We can check that new table is created in sales.db with the help of SQLiteStudio tool.

    Sales.db New Table

    Invoices class applies ForeignKey construct on custid attribute. This directive indicates that values in this column should be constrained to be values present in id column in customers table. This is a core feature of relational databases, and is the “glue” that transforms unconnected collection of tables to have rich overlapping relationships.

    A second directive, known as relationship(), tells the ORM that the Invoice class should be linked to the Customer class using the attribute Invoice.customer. The relationship() uses the foreign key relationships between the two tables to determine the nature of this linkage, determining that it is many to one.

    An additional relationship() directive is placed on the Customer mapped class under the attribute Customer.invoices. The parameter relationship.back_populates is assigned to refer to the complementary attribute names, so that each relationship() can make intelligent decision about the same relationship as expressed in reverse. On one side, Invoices.customer refers to Invoices instance, and on the other side, Customer.invoices refers to a list of Customers instances.

    The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship.

    Following are the basic Relationship Patterns found −

    One To Many

    A One to Many relationship refers to parent with the help of a foreign key on the child table. relationship() is then specified on the parent, as referencing a collection of items represented by the child. The relationship.back_populates parameter is used to establish a bidirectional relationship in one-to-many, where the “reverse” side is a many to one.

    Many To One

    On the other hand, Many to One relationship places a foreign key in the parent table to refer to the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created. Here again the relationship.back_populates parameter is used for Bidirectionalbehaviour.

    One To One

    One To One relationship is essentially a bidirectional relationship in nature. The uselist flag indicates the placement of a scalar attribute instead of a collection on the “many” side of the relationship. To convert one-to-many into one-to-one type of relation, set uselist parameter to false.

    Many To Many

    Many to Many relationship is established by adding an association table related to two classes by defining attributes with their foreign keys. It is indicated by the secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link. The relationship.back_populates parameter for each relationship() establishes a bidirectional relationship. Both sides of the relationship contain a collection.


    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

  • Khóa học miễn phí Textual SQL nhận dự án làm có lương

    SQLAlchemy ORM – Textual SQL



    Earlier, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view.

    Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most applicable methods accept it. For example, filter() and order_by().

    In the example given below, the filter() method translates the string “id<3” to the WHERE id<3

    from sqlalchemy import text
    for cust in session.query(Customers).filter(text("id<3")):
       print(cust.name)
    

    The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below −

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

    From our sample data in Customers table, two rows will be selected and name column will be printed as follows −

    Ravi Kumar
    Komal Pande
    

    To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method.

    cust = session.query(Customers).filter(text("id = :value")).params(value = 1).one()
    

    The effective SQL displayed on Python console will be as given below −

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

    To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement().

    session.query(Customers).from_statement(text("SELECT * FROM customers")).all()
    

    The result of above code will be a basic SELECT statement as given below −

    SELECT * FROM customers
    

    Obviously, all records in customers table will be selected.

    The text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method.

    stmt = text("SELECT name, id, name, address, email FROM customers")
    stmt = stmt.columns(Customers.id, Customers.name)
    session.query(Customers.id, Customers.name).from_statement(stmt).all()
    

    The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method −

    SELECT name, id, name, address, email FROM customers
    

    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

  • Khóa học miễn phí Filter Operators nhận dự án làm có lương

    SQLAlchemy ORM – Filter Operators



    Now, we will learn the filter operations with their respective codes and output.

    Equals

    The usual operator used is == and it applies the criteria to check equality.

    result = session.query(Customers).filter(Customers.id == 2)
    
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    SQLAlchemy will send following SQL expression −

    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 = ?
    

    The output for the above code is as follows −

    ID: 2 Name: Komal Pande Address: Banjara Hills Secunderabad Email: komal@gmail.com
    

    Not Equals

    The operator used for not equals is != and it provides not equals criteria.

    result = session.query(Customers).filter(Customers.id! = 2)
    
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    The resulting SQL expression is −

    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 != ?
    

    The output for the above lines of code is as follows −

    ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com
    ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
    ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com
    

    Like

    like() method itself produces the LIKE criteria for WHERE clause in the SELECT expression.

    result = session.query(Customers).filter(Customers.name.like(''Ra%''))
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    Above SQLAlchemy code is equivalent to following SQL expression −

    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.name LIKE ?
    

    And the output for the above code is −

    ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com
    ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
    

    IN

    This operator checks whether the column value belongs to a collection of items in a list. It is provided by in_() method.

    result = session.query(Customers).filter(Customers.id.in_([1,3]))
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    Here, the SQL expression evaluated by SQLite engine will be as follows −

    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 IN (?, ?)
    

    The output for the above code is as follows −

    ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com
    ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
    

    AND

    This conjunction is generated by either putting multiple commas separated criteria in the filter or using and_() method as given below −

    result = session.query(Customers).filter(Customers.id>2, Customers.name.like(''Ra%''))
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    from sqlalchemy import and_
    result = session.query(Customers).filter(and_(Customers.id>2, Customers.name.like(''Ra%'')))
    
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    Both the above approaches result in similar SQL expression −

    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 > ? AND customers.name LIKE ?
    

    The output for the above lines of code is −

    ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
    

    OR

    This conjunction is implemented by or_() method.

    from sqlalchemy import or_
    result = session.query(Customers).filter(or_(Customers.id>2, Customers.name.like(''Ra%'')))
    
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    As a result, SQLite engine gets following equivalent SQL expression −

    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 > ? OR customers.name LIKE ?
    

    The output for the above code is as follows −

    ID: 1 Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com
    ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
    ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com
    

    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

  • 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

  • Khóa học miễn phí Applying Filter nhận dự án làm có lương

    SQLAlchemy ORM – Applying Filter



    In this chapter, we will discuss how to apply filter and also certain filter operations along with their codes.

    Resultset represented by Query object can be subjected to certain criteria by using filter() method. The general usage of filter method is as follows −

    session.query(class).filter(criteria)
    

    In the following example, resultset obtained by SELECT query on Customers table is filtered by a condition, (ID>2) −

    result = session.query(Customers).filter(Customers.id>2)
    

    This statement will translate into following SQL expression −

    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 > ?
    

    Since the bound parameter (?) is given as 2, only those rows with ID column>2 will be displayed. The complete code is given below −

    from sqlalchemy import Column, Integer, String
    from sqlalchemy import create_engine
    engine = create_engine(''sqlite:///sales.db'', echo = True)
    from sqlalchemy.ext.declarative import declarative_base
    Base = declarative_base()
    
    class Customers(Base):
       __tablename__ = ''customers''
    
       id = Column(Integer, primary_key = True)
       name = Column(String)
    
       address = Column(String)
       email = Column(String)
    
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind = engine)
    session = Session()
    result = session.query(Customers).filter(Customers.id>2)
    
    for row in result:
       print ("ID:", row.id, "Name: ",row.name, "Address:",row.address, "Email:",row.email)
    

    The output displayed in the Python console is as follows −

    ID: 3 Name: Rajender Nath Address: Sector 40, Gurgaon Email: nath@gmail.com
    ID: 4 Name: S.M.Krishna Address: Budhwar Peth, Pune Email: smk@gmail.com
    

    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

  • Khóa học miễn phí Updating Objects nhận dự án làm có lương

    SQLAlchemy ORM – Updating Objects



    In this chapter, we will see how to modify or update the table with desired values.

    To modify data of a certain attribute of any object, we have to assign new value to it and commit the changes to make the change persistent.

    Let us fetch an object from the table whose primary key identifier, in our Customers table with ID=2. We can use get() method of session as follows −

    x = session.query(Customers).get(2)
    

    We can display contents of the selected object with the below given code −

    print ("Name: ", x.name, "Address:", x.address, "Email:", x.email)
    

    From our customers table, following output should be displayed −

    Name: Komal Pande Address: Koti, Hyderabad Email: komal@gmail.com
    

    Now we need to update the Address field by assigning new value as given below −

    x.address = ''Banjara Hills Secunderabad''
    session.commit()
    

    The change will be persistently reflected in the database. Now we fetch object corresponding to first row in the table by using first() method as follows −

    x = session.query(Customers).first()
    

    This will execute following SQL expression −

    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 will be LIMIT = 1 and OFFSET = 0 respectively which means first row will be selected.

    print ("Name: ", x.name, "Address:", x.address, "Email:", x.email)
    

    Now, the output for the above code displaying the first row is as follows −

    Name: Ravi Kumar Address: Station Road Nanded Email: ravi@gmail.com
    

    Now change name attribute and display the contents using the below code −

    x.name = ''Ravi Shrivastava''
    print ("Name: ", x.name, "Address:", x.address, "Email:", x.email)
    

    The output of the above code is −

    Name: Ravi Shrivastava Address: Station Road Nanded Email: ravi@gmail.com
    

    Even though the change is displayed, it is not committed. You can retain the earlier persistent position by using rollback() method with the code below.

    session.rollback()
    
    print ("Name: ", x.name, "Address:", x.address, "Email:", x.email)
    

    Original contents of first record will be displayed.

    For bulk updates, we shall use update() method of the Query object. Let us try and give a prefix, ‘Mr.’ to name in each row (except ID = 2). The corresponding update() statement is as follows −

    session.query(Customers).filter(Customers.id! = 2).
    update({Customers.name:"Mr."+Customers.name}, synchronize_session = False)
    

    The update() method requires two parameters as follows −

    • A dictionary of key-values with key being the attribute to be updated, and value being the new contents of attribute.

    • synchronize_session attribute mentioning the strategy to update attributes in the session. Valid values are false: for not synchronizing the session, fetch: performs a select query before the update to find objects that are matched by the update query; and evaluate: evaluate criteria on objects in the session.

    Three out of 4 rows in the table will have name prefixed with ‘Mr.’ However, the changes are not committed and hence will not be reflected in the table view of SQLiteStudio. It will be refreshed only when we commit the session.


    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