Peewee - 使用PostgreSQL



Peewee 也支援 PostgreSQL 資料庫。它為此目的提供了 **PostgresqlDatabase** 類。本章我們將看到如何使用 Peewee 模型連線到 PostgreSQL 資料庫並在其中建立表。

與 MySQL 一樣,無法使用 Peewee 的功能在 PostgreSQL 伺服器上建立資料庫。必須使用 PostgreSQL shell 或 PgAdmin 工具手動建立資料庫。

首先,我們需要安裝 PostgreSQL 伺服器。對於 Windows 作業系統,我們可以下載 https://get.enterprisedb.com/postgresql/postgresql-13.1-1-windows-x64.exe 並安裝。

接下來,使用 pip 安裝程式安裝 PostgreSQL 的 Python 驅動程式 – **Psycopg2** 包。

pip install psycopg2

然後啟動伺服器,可以透過 PgAdmin 工具或 psql shell 啟動。現在我們可以建立資料庫了。執行以下 Python 指令碼在 PostgreSQL 伺服器上建立 mydatabase 資料庫。

import psycopg2

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

檢查資料庫是否已建立。在 psql shell 中,可以使用 `\l` 命令進行驗證。

List of Databases

要宣告 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 並獲取其中的表列表。

My Database

要檢查新建立的 MyUser 資料庫的結構,請在 shell 中執行以下查詢:

My User Database
廣告