Discover Peewee, a small and expressive ORM perfect for simpler database applications. Learn to define models, query databases, and perform CRUD operations with minimal boilerplate code - ideal for scripts, small applications, and rapid prototyping.
This document explains the Peewee ORM example provided in peewee_example.py.
The example shows how to:
import os from peewee import Model, SqliteDatabase, CharField db_file = "peewee_example.db" if os.path.exists(db_file): os.remove(db_file) db = SqliteDatabase(db_file)
This section imports necessary modules and sets up the SQLite database file. If the file already exists, it's removed to start fresh. We then create a SqliteDatabase instance.
class User(Model): username = CharField(unique=True) email = CharField(unique=True) class Meta: database = db def __str__(self): return f"User: {self.username}, Email: {self.email}"
Here, we define the User model. It has two fields: username and email. The Meta class specifies which database to use. The __str__ method provides a string representation of the object.
def run_example(): db.connect() db.create_tables([User]) try: new_user = User.create(username='alice', email='alice@example.com') user = User.get(User.username == 'alice') print(user) except Exception as e: print(f"An error occurred: {e}") finally: db.close()
This function demonstrates:
if __name__ == "__main__": run_example() print(f"SQLite database created at: {os.path.abspath(db_file)}")
This section runs the example when the script is executed directly and prints the location of the created database file.
To run this example:
Ensure you have Peewee installed:
pip install peewee
Run the script:
python peewee_example.py
The script will create a SQLite database file, add a user to it, retrieve and print the user's information, and then display the location of the created database file.