- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Object Relational Mapper in SQLAlchemy
In this part of the SQLAlchemy tutorial, we cover the SQLAlchemy's Object Relational Mapper.
Object Relational Mapping
Programming with the Python database API gives developers full power of direct access to the database. This direct access has some disadvantages too. They are noticeable especially in larger projects. We mix two languages together: SQL and Python. The consequence is that it makes SQL statements harder to test and maintain. In a typical web application, we have HTML, CSS, JavaScript, in addition to Python and SQL (or any other server side programming language). The Python and SQL tied together makes the project even more complex. In programming theory, we try to separate the business logic from the data access and from the presentation. Therefore, a solution that separates Python code from the SQL code is desirable.
Another problem is what we call the object-relational impedance mismatch. It is a set of conceptual and technical difficulties that are often encountered when a relational database management system is being used by a program written in an object-oriented programming language or style. In Python, we work with data that are placed within objects. In database systems the data is stored in tables. The programmers need to do conversions between the two ways of handling data. This is something that is not related to the core problems of our applications.
One of the solutions is object-relational mapping. ORM tools address the above mentioned issues. There are several ORM tools for the Python language. The SQLAlchemy is one of the most widely used ones.
SQLAlchemy ORM
The SQLAlchemy Object Relational Mapper maps (a) user-defined Python classes to database tables, (b) table rows to instance objects, and (c) columns to instance attributes. The SQLAlchemy ORM is built on the SQLAlchemy Expression Language.
When using ORM, we first configure database tables that we will be using. Then we define classes that will be mapped to them. Modern SQLAlchemy uses Declarative system to do these tasks. A declarative base class is created, which maintains a catalog of classes and tables. A declarative base class is created with the declarative_base()
function.
Session
After we have done the configurations, we create a session. A Session is the primary interface for persistence operations in the SQLAlchemy ORM. It establishes and maintains all conversations between our program and the database.
Creating a table
The following program creates a table in memory and then prints the data to the console.
orm_create_table.py
#!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker eng = create_engine('sqlite:///:memory:') Base = declarative_base() class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String) Price = Column(Integer) Base.metadata.bind = eng Base.metadata.create_all() Session = sessionmaker(bind=eng) ses = Session() ses.add_all( [Car(Id=1, Name='Audi', Price=52642), Car(Id=2, Name='Mercedes', Price=57127), Car(Id=3, Name='Skoda', Price=9000), Car(Id=4, Name='Volvo', Price=29000), Car(Id=5, Name='Bentley', Price=350000), Car(Id=6, Name='Citroen', Price=21000), Car(Id=7, Name='Hummer', Price=41400), Car(Id=8, Name='Volkswagen', Price=21600)]) ses.commit() rs = ses.query(Car).all() for car in rs: print car.Name, car.Price
Eight cars are created in the Cars table.
Base = declarative_base()
A declarative base class is created with the declarative_base()
function.
class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String) Price = Column(Integer)
The user-defined Car
class is mapped to the Cars table. The class inherits from the declarative base class.
Base.metadata.bind = eng
The declarative Base
is bound to the database engine.
Base.metadata.create_all()
The create_all()
method creates all configured tables; in our case, there is only one table.
Session = sessionmaker(bind=eng) ses = Session()
A session object is created.
ses.add_all( [Car(Id=1, Name='Audi', Price=52642), Car(Id=2, Name='Mercedes', Price=57127), ...
With the add_all()
method, we add the specified instances of Car
classes to the session.
ses.commit()
The changes are committed to the database with the commit()
method.
rs = ses.query(Car).all()
We query for all data from the Cars table. The query()
method loads all instances of the Car class and its all()
method returns all results represented by the query as a list.
for car in rs: print car.Name, car.Price
We iterate through the result set and print two columns for all returned rows.
$ ./orm_create_table.py Audi 52642 Mercedes 57127 Skoda 9000 Volvo 29000 Bentley 350000 Citroen 21000 Hummer 41400 Volkswagen 21600
This is the output of the example.
Adding a new car
In the next example, we add a single car to the Cars table.
orm_add_car.py
#!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker eng = create_engine('sqlite:///test.db') Base = declarative_base() class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String) Price = Column(Integer) Session = sessionmaker(bind=eng) ses = Session() c1 = Car(Name='Oldsmobile', Price=23450) ses.add(c1) ses.commit() rs = ses.query(Car).all() for car in rs: print car.Name, car.Price
The script connects to the SQLite database and adds a new row to the Cars table.
eng = create_engine('sqlite:///test.db')
We connect to the SQLite test.db
database.
Base = declarative_base() class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String) Price = Column(Integer)
The mapping of the user-defined class to the database table is performed.
Session = sessionmaker(bind=eng) ses = Session()
The session object, which is ORM's intermediary to the database, is created.
c1 = Car(Name='Oldsmobile', Price=23450)
A new instance of a mapped Car
class is created.
ses.add(c1)
The add()
method adds the new object to the session.
ses.commit()
The changes are committed to the database.
$ ./orm_add_car.py Audi 52642 Mercedes 57127 Skoda 9000 Volvo 29000 Bentley 350000 Citroen 21000 Hummer 41400 Volkswagen 21600 Oldsmobile 23450
We verify that the new car was successfully added to the database.
Filtering data
The session query's filter()
method is used to apply a filter criterion on the query object.
orm_query_like.py
#!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker eng = create_engine('sqlite:///test.db') Base = declarative_base() Base.metadata.bind = eng class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String) Price = Column(Integer) Session = sessionmaker(bind=eng) ses = Session() rs = ses.query(Car).filter(Car.Name.like('%en')) for car in rs: print car.Name, car.Price
The example prints cars whose names end in 'en' string.
rs = ses.query(Car).filter(Car.Name.like('%en'))
The filter()
method takes a filtering criterion, which is an SQL expression object. The criterion is created with the like()
method.
$ ./orm_query_like.py Citroen 21000 Volkswagen 21600
There are two cars in the table that end in 'en' string.
The in_()
method implements the SQL IN
operator.
orm_query_in.py
#!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker eng = create_engine('sqlite:///test.db') Base = declarative_base() class Car(Base): __tablename__ = "Cars" Id = Column(Integer, primary_key=True) Name = Column(String) Price = Column(Integer) Session = sessionmaker(bind=eng) ses = Session() rs = ses.query(Car).filter(Car.Id.in_([2, 4, 6, 8])) for car in rs: print car.Id, car.Name, car.Price
The code example selects and prints columns for rows with Ids chosen by the SQL IN
operator.
rs = ses.query(Car).filter(Car.Id.in_([2, 4, 6, 8]))
The filtering criterion is created by the in_()
method. The method takes a list of Ids.
$ ./orm_query_in.py 2 Mercedes 57127 4 Volvo 29000 6 Citroen 21000 8 Volkswagen 21600
This is the output of the example.
Foreign key
In the last example, we deal with a relationship between two tables. A foreign key is established.
orm_foreign_key.py
#!/usr/bin/python # -*- coding: utf-8 -*- from sqlalchemy import create_engine, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String from sqlalchemy.orm import sessionmaker, relationship eng = create_engine('sqlite:///test.db') Base = declarative_base() class Author(Base): __tablename__ = "Authors" AuthorId = Column(Integer, primary_key=True) Name = Column(String) Books = relationship("Book") class Book(Base): __tablename__ = "Books" BookId = Column(Integer, primary_key=True) Title = Column(String) AuthorId = Column(Integer, ForeignKey("Authors.AuthorId")) Author = relationship("Author") Session = sessionmaker(bind=eng) ses = Session() res = ses.query(Author).filter(Author.Name=="Leo Tolstoy").first() for book in res.Books: print book.Title res = ses.query(Book).filter(Book.Title=="Emma").first() print res.Author.Name
We have Author
and Book
classes which are mapped to the Authors
and Books
database tables. (The SQL to create the tables is listed in the first chapter). A foreign key constraint is implemented between the two tables. A foreign key is defined by the ForeignKey
type and the relationship()
function.
Books = relationship("Book")
A one to many relationship is built between the two classes. The first argument of the relationship()
function is the name of a class we build the relationship with. As a result, the author object will have a Books
attribute.
AuthorId = Column(Integer, ForeignKey("Authors.AuthorId"))
The AuthorId
of the Book
class is a foreign key. It is defined by the ForeignKey
type. It references the AuthorId
column in the Authors
table.
Author = relationship("Author")
This line creates an Author
attribute for the Book
class.
res = ses.query(Author).filter(Author.Name=="Leo Tolstoy").first()
In this query, we get all books written by Leo Tolstoy. The filter()
method applies a filtering criterion on the query. The first()
method gets the author object.
for book in res.Books: print book.Title
We go through the result set and print all the retrieved books. The Books
attribute was created with the relationship()
function.
res = ses.query(Book).filter(Book.Title=="Emma").first() print res.Author.Name
This query returns the author of the Emma
title. The query returns the book object, which has a built-in Author
attribute.
$ ./orm_foreign_key.py War and Peace Anna Karenia Jane Austen
This is the output of the example.
In this part of the SQLAlchemy tutorial, we worked with SQLAlchemy's ORM.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论