Detailed Explanation of Mapping and Declarative of python SQLAlchemy

  • 2021-07-09 08:43:26
  • OfStack

Engine and Connection in vSQLAlchemy have been introduced earlier, which are used to operate on row SQL (native sql statement), while ORM (Object Relational Mapper) is a technology to operate table data with object-oriented thinking. The so-called ORM is a mapping relationship between Python objects and data tables.

How did SQLAlchemy map an Python object to every record in a table in a database? Through an mapping function

Let's take an example first:


from sqlalchemy import Table, MetaData, Column, Integer, String,
from sqlalchemy.orm import mapper

#  Metadata of database, you can think of it as 1 Containers that hold all the table structures 
metadata = MetaData()

#  In the database news_article Table 
article = Table("news_article", metadata,
        Column("id", Integer, primary_key=True),
        Column("title", String)
        )

#  This is 1 An ordinary one Article Class 
class Article:
  def __init__(self, title):
    self.title = title

#  Pass mapper Function for mapping association 
mapper(Article, article)

How to use it after association? Look at the example:


from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
#  Pass Artcile Class to query id==4554 This is performed entirely in an object-oriented manner sql It's over 
#  The result returned is Article Instance object of 
result = session.query(Article).filter(Article.id==4554).first()
print(result.id) # 4554
print(result.title) # xxxxxxxxx

After the mapper function is mapped, the returned result will be automatically constructed into an Article object with id attribute, which is the magic of ORM.

However, the new ORM mapping does not need to manually associate the relationship between table and classes through mapping function, but can directly define a class through the declaration (Declarative) system (I don't know if this translation is correct), which will directly map to the database table. declarative puts Table, mapper and classes into one block for declaration, thus realizing ORM mapping. Take an example:


from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Article(Base):
  __tablename__ = 'news_article'
  id = Column(Integer, primary_key=True)
  title = Column(String(50))

Is it much simpler? There is no definition of Table, no function of mapper, only the definition of a class. This class must inherit the base class Base, and Base is our declaration system, thus completing the mapping relationship between Table and the class, and the operations behind it are all completed through a declaration system constructed by an declarative_base factory method.

We call Article a mapping class, which holds references to Table and mapper functions.


>>> print(Article.__table__)
news_article

>>>print(Article.__mapper__)
Mapper|Article|news_article

#  Previous will be metadata  It can be passed through  Base  Get 
>>>print(Base.metadata)
MetaData(bind=None)

What's the use of MetaData? It can be used to create tables or delete tables.


Related articles: