Peewee 简明教程

Peewee - Using PostgreSQL

Peewee 也支持 PostgreSQL 数据库。它为该目的提供了 PostgresqlDatabase 类。在本章中,我们将看到如何借助 Peewee 模型连接到 Postgres 数据库并在其中创建一个表。

Peewee supports PostgreSQL database as well. It has PostgresqlDatabase class for that purpose. In this chapter, we shall see how we can connect to Postgres database and create a table in it, with the help of Peewee model.

就像 MySQL 的情况一样,使用 Peewee 的功能无法在 Postgres 服务器上创建数据库。必须使用 Postgres shell 或 PgAdmin 工具手动创建数据库。

As in case of MySQL, it is not possible to create database on Postgres server with Peewee’s functionality. The database has to be created manually using Postgres shell or PgAdmin tool.

首先,我们需要安装 Postgres 服务器。对于 Windows 操作系统,我们可以下载 https://get.enterprisedb.com/postgresql/postgresql-13.1-1-windows-x64.exe 并安装它。

First, we need to install Postgres server. For windows OS, we can download https://get.enterprisedb.com/postgresql/postgresql-13.1-1-windows-x64.exe and install.

接下来,使用 pip 安装程序安装 Postgres 的 Python 驱动程序,即 Psycopg2 软件包。

Next, install Python driver for Postgres – Psycopg2 package using pip installer.

pip install psycopg2

然后,从 PgAdmin 工具或 psql shell 启动服务器。我们现在可以创建数据库。运行以下 Python 脚本可在 Postgres 服务器上创建 mydatabase。

Then start the server, either from PgAdmin tool or psql shell. We are now in a position to create a database. Run following Python script to create mydatabase on Postgres server.

import psycopg2

conn = psycopg2.connect(host='localhost', user='postgres', password='postgres')
conn.cursor().execute('CREATE DATABASE mydatabase')
conn.close()

检查数据库是否已创建。在 psql shell 中,可以使用 \l 命令验证其是否已创建:

Check that the database is created. In psql shell, it can be verified with \l command −

list of databases

要声明 MyUser 模型并在上述数据库中创建同名表,请运行以下 Python 代码:

To declare MyUser model and create a table of same name in above database, run following Python code −

from peewee import *

db = PostgresqlDatabase('mydatabase', host='localhost', port=5432, user='postgres', password='postgres')
class MyUser (Model):
   name=TextField()
   city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
   age=IntegerField()
   class Meta:
      database=db
      db_table='MyUser'

db.connect()
db.create_tables([MyUser])

我们可以验证表是否已创建。在 shell 内,连接到 mydatabase 并获取其中的表列表。

We can verify that table is created. Inside the shell, connect to mydatabase and get list of tables in it.

mydatabase

要检查新创建的 MyUser 数据库的结构,请在 shell 中运行以下查询。

To check structure of newly created MyUser database, run following query in the shell.

myuser database