← Back to Libraries🗄️ Database & SQL
📦

Mastering Peewee: The Ultimate Lightweight ORM for Python

Learn everything about Peewee, a lightweight ORM that simplifies database interaction, suitable for Python SQLite and other databases.

pip install peewee

Overview

What is peewee and why use it?

Key features and capabilities

Installation instructions

Basic usage examples

Common use cases

Best practices and tips

Common Use Cases

Code Examples

Getting Started with peewee

import peewee\n\n# Define a simple model\nclass BaseModel(peewee.Model):\n    pass\n\nclass User(BaseModel):\n    username = peewee.CharField()\n    email = peewee.CharField()\n\n# Connecting to a SQLite database\nsqlite_db = peewee.SqliteDatabase('my_app.db')\n\nUser._meta.database = sqlite_db\n\n# Create the table\nsqlite_db.connect()\nsqlite_db.create_tables([User])\n\n# Insert a new user\nnew_user = User.create(username='john_doe', email='john@example.com')\n\n# Querying the database\nuser = User.get(User.username == 'john_doe')\nprint(user.email)

Advanced peewee Example

import peewee\n\n# Advanced query with joining\nclass Blog(BaseModel):\n    title = peewee.CharField()\n    content = peewee.TextField()\n    user = peewee.ForeignKeyField(User, backref='blogs')\n\n# Create the table\nsqlite_db.create_tables([Blog])\n\n# Insert a new blog\nnew_blog = Blog.create(title='My First Blog', content='This is a blog post.', user=new_user)\n\n# Querying with join\nblogs = (Blog\n         .select(Blog, User)\n         .join(User)\n         .where(User.username == 'john_doe'))\n\nfor blog in blogs:\n    print(blog.title, blog.user.username)

Alternatives

Common Methods

create

Creates a new record in the database

get

Retrieves a single record based on conditions

select

Selects records with optional conditions

More Database & SQL Libraries