- Peewee - Discussion
- Peewee - Useful Resources
- Peewee - Quick Guide
- Peewee - Using CockroachDB
- Peewee - PostgreSQL & MySQL Extensions
- Peewee - SQLite Extensions
- Peewee - Integration with Web Frameworks
- Peewee - Query Builder
- Peewee - Database Errors
- Peewee - Atomic Transactions
- Peewee - User defined Operators
- Peewee - Retrieving Row Tuples/Dictionaries
- Peewee - SQL Functions
- Peewee - Counting & Aggregation
- Peewee - Sorting
- Peewee - Subqueries
- Peewee - Relationships & Joins
- Peewee - Connection Management
- Peewee - Defining Database Dynamically
- Peewee - Using PostgreSQL
- Peewee - Using MySQL
- Peewee - Constraints
- Peewee - Create Index
- Peewee - Delete Records
- Peewee - Update Existing Records
- Peewee - Primary & Composite Keys
- Peewee - Filters
- Peewee - Select Records
- Peewee - Insert a New Record
- Peewee - Field Class
- Peewee - Model
- Peewee - Database Class
- Peewee - Overview
- Peewee - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Peewee - Using PostgreSQL
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.
As in case of MySQL, it is not possible to create database on Postgres server with Peewee’s functionapty. The database has to be created manually using Postgres shell or PgAdmin tool.
First, we need to install Postgres server. For windows OS, we can download
and install.Next, install Python driver for Postgres – Psycopg2 package using pip installer.
pip install psycopg2
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()
Check that the database is created. In psql shell, it can be verified with l command −
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])
We can verify that table is created. Inside the shell, connect to mydatabase and get pst of tables in it.
To check structure of newly created MyUser database, run following query in the shell.
Advertisements