Peewee使用PostgreSQL

Peewee 也支持 PostgreSQL 数据库,它有PostgresqlDatabase类。在本文中,我们将看到如何借助 Peewee 模型连接到 Postgres 数据库并在其中创建表。

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

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

接下来,使用 pip 安装程序为 Postgres 安装 Python 驱动程序 – Psycopg2包。

pip install psycopg2

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

import psycopg2

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

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

Peewee使用PostgreSQL

声明 MyUser 模型并在上述数据库中创建一个同名表,执行如下 Python 代码 –

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 并获取其中的表列表。

Peewee使用PostgreSQL

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

Peewee使用PostgreSQL

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!