SQLAlchemy Core
- Using Set Operations
- Using Functions
- Using Conjunctions
- Using Joins
- Multiple Table Deletes
- Parameter-Ordered Updates
- Using Multiple Table Updates
- Using Multiple Tables
- Using DELETE Expression
- Using UPDATE Expression
- Using Aliases
- Using Textual SQL
- Selecting Rows
- Executing Expression
- SQL Expressions
- Creating Table
- Connecting to Database
- Expression Language
SQLAlchemy ORM
- Dialects
- Many to Many Relationships
- Deleting Related Objects
- Eager Loading
- Common Relationship Operators
- Working with Joins
- Working with Related Objects
- Building Relationship
- Textual SQL
- Returning List and Scalars
- Filter Operators
- Applying Filter
- Updating Objects
- Using Query
- Adding Objects
- Creating Session
- Declaring Mapping
SQLAlchemy Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
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 pst. We can assign items in the pst 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 −
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 pst 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()Advertisements