Home Backend Development Python Tutorial Python ORM框架SQLAlchemy学习笔记之关系映射实例

Python ORM框架SQLAlchemy学习笔记之关系映射实例

Jun 16, 2016 am 08:43 AM
orm python sqlalchemy relationship mapping

昨天简单介绍了SQLAlchemy的使用,但是没有能够涉及其最精彩的ORM部分,今天我将简单说明一下,当然主要还是讲解官方文档的内容,由于是学习笔记,有可能存在精简或者自己理解的部分,不做权威依据。

当我们开始使用ORM,一种可配置的结构可以用于描述我们的数据库表,稍后我们定义的类将会被映射到这些表上。当然现代的SQLAlchemy(新版本SQLAlchemy,原文是modern SQLAlchemy)使用Declarative把这两件事一起做了,即允许我们把创建类和描述定义数据库表以及它们之间的映射关系一次搞定。

这段话是什么意思呢?简单来说吧,SQLAlchemy分为Classic (经典模式)和Modern (现代模式),Classic定义数据库表的模式比较传统,需要先描述这个表。

1. Classic 映射

比如以官方文档中的例子,我们拥有表结构如下:

复制代码 代码如下:

CREATE TABLE [users] (
  [id]       INTEGER PRIMARY KEY,
  [name]     TEXT NOT NULL,
  [fullname] TEXT NOT NULL,
  [password] TEXT NOT NULL
);

下面我们描述这张表:

复制代码 代码如下:

from sqlalchemy import Table, MetaData, Column, Integer, String

metadata = MetaData()

user = Table('users', metadata,
            Column('id', Integer, primary_key=True),
            Column('name', String(50)),
            Column('fullname', String(50)),
            Column('password', String(12))
        )
好,这样我们的表算是描述完成了,接下来我们需要定义我们的Python类,比如这样的:
复制代码 代码如下:

class User(object):
    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password
如何让我们定义的类与之前描述的表结构发生映射关系就是我们接下来要做的:
复制代码 代码如下:

from sqlalchemy.orm import mapper
mapper(User, user)
大家注意到mapper函数,第一个参数是我们类的名称,第二个参数是我们先前描述的表定义。

这就是传统的定义ORM的方法,有关这个方法的更多信息,可以阅读文档Mapper Configuration,以后有机会再和大家详谈。

2. Modern 映射

当大家都乐此不疲的定义描述表,定义类,再映射来实现ORM的时候,SQLAlchemy团队搞出了更简单的映射方法,那就是Modern模式了,即通过定义映射类来一次性完成所有任务。

为了定义的类能够被SQLAlchemy管理,所以引入了Declarative这个概念,也就是说我们所有的类必须是Declarative基类的子类,而这个基类可以通过下面的办法来获取:

复制代码 代码如下:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
当然一个程序内,这个基类最好是唯一的,建议存储在全局变量比如Base中供所有映射类使用。

现在通过刚才的代码我们得到了名为Base的基类,通过这个基类我们可以定义N多的映射子类,而这些子类都能被SQLAlchemy Declarative系统管理到。

下面我们还是看刚才的那个users表的例子:

复制代码 代码如下:

from sqlalchemy import Column, Integer, String
class User(Base):
     __tablename__ = 'users'

     id = Column(Integer, primary_key=True)
     name = Column(String)
     fullname = Column(String)
     password = Column(String)

     def __init__(self, name, fullname, password):
         self.name = name
         self.fullname = fullname
         self.password = password

     def __repr__(self):
        return "" % (self.name, self.fullname, self.password)
就这段代码就完成了我们先前在Classic中需要的三步,代码比原先更简洁和容易管理了,同刚才Classic中Table定义的Column,这个代表数据库表中的列,当然Integer和String代表着数据库表的字段类型了。

这样User类就建立起与数据库表的映射,真实表的名字可以使用__tablename__指明,然后是表列的集合,包括id、name、fullname以及password,当然想必大家已经知道了,我们通过primary_key=True已经指明id为主键了。当然一些数据库表可能不包含有主键(例如视图View,当然视图也可以被映射),ORM为了能够实际映射表需要至少一个列被定义为主键列。多列,比如复合多主键也能够被很好地映射支持。

大家可能注意到User类中还包含有通常意义上的Python魔术方法,包含__init__()初始化类(构造方法)以及__repr__()字符串化支持方法,当然这些都是可选的,如果需要这个类可以加入程序所需要的任意多方法或者属性,你只要把这个类看作一个普通的Python类就可以了。

当然User类唯一不能马虎的就是必须继承至Base,这个Base就是刚才我们通过declarative_base()生成的类,通过它我们可以接下来让SQLAlchemy Declarative系统管理并操作这些映射类和数据库表。

实际上包括继承的Base类,所有的类都应该是Python的新式类(new style class),关于新式类的更多信息可以参考Python手册。

随着我们的User映射类通过Declarative系统构造成功,我们就拥有了相关的定义信息,比如在Classic定义中介绍的Table()描述,也包含映射到表的类,就是User自身,我们可以通过User.__table__来查看我们的表描述情况:

复制代码 代码如下:

>>> User.__table__
Table('users', MetaData(None),
    Column('id', Integer(), table=, primary_key=True, nullable=False),
    Column('name', String(), table=),
    Column('fullname', String(), table=),
    Column('password', String(), table=), schema=None)
当然找到描述表的数据结构,也应该能找到mapper,我们的Mapper对象可以通过__mapper__属性来获取,比如这样的:
复制代码 代码如下:

>>> User.__mapper__

同样的MetaData可以通过.metadata属性找到。

好啦,下面轻松一下,见证奇迹的时刻,我们需不需要定义创建好实体数据库然后再定义ORM?对于SQLAlchemy来说这些都是小事一桩,其都可以给你一手包办,也就是说你可以完全不必理会数据库,交给SQLAlchemy就可以了,比如通过MetaData.create_all()并将engine参数传入即可(什么是engine?参考我的笔记1),比如通过下面的方式创建我们的users表。

复制代码 代码如下:

>>> Base.metadata.create_all(engine)
PRAGMA table_info("users")
()
CREATE TABLE users (
    id INTEGER NOT NULL,
    name VARCHAR,
    fullname VARCHAR,
    password VARCHAR,
    PRIMARY KEY (id)
)
()
COMMIT
由于我们开启了engine的echo=True,所以在交互命令下SQLAlchemy把SQL语句也输出了,正好可以检验是否符合我们的要求。

这样简单的create_all()我们就轻松建立起先前ORM映射定义的表啦。

时间不早了,今天先聊到这儿,下次再谈SQLAlchemy的其他特性。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles