Python peewee example
Python peewee example
I'll respond in English only.
Here's an example of using the Peewee ORM with Python to interact with a SQLite database:
First, let's install Peewee:
pip install peewee
Now, let's create a simple database schema for this example. We're going to have two tables: people
and pets
.
import os
Delete the existing db file if it exists
if os.path.exists('mydatabase.db'):
os.remove('mydatabase.db')
from peewee import *
Create the database and models
db = SqliteDatabase('mydatabase.db')
class Person(Model):
class Meta:
database = db
name = CharField()
age = IntegerField()
class Pet(Model):
class Meta:
database = db
owner = ForeignKeyField(Person, related_name='pets')
animal_type = CharField()
name = CharField()
Create the tables
db.create_tables([Person, Pet])
In this example, we import peewee
and use it to create a SQLite database. We define two models: Person
and Pet
. Each model has attributes that match the columns in their respective tables.
Then, we call the create_tables()
method on our database instance, passing it a list of the models. This will create the corresponding tables in the database if they don't already exist, or update them if they do.
Let's add some data to our tables:
# Create some people
john = Person(name='John', age=30)
jane = Person(name='Jane', age=25)
Create some pets
mittens = Pet(owner=john, animal_type='cat', name='Mittens')
fido = Pet(owner=john, animal_type='dog', name='Fido')
whiskers = Pet(owner=jane, animal_type='cat', name='Whiskers')
Save the changes to the database
db.commit()
In this example, we create some instances of our Person
and Pet
models, and then save them to the database using the db.commit()
method.
Now let's query our data:
# Get all people who have a cat or dog
people_with_pets = Person.select().where((Person.id << Pet.select().where(Pet.owner == Person)).alias())
for person in people_with_pets:
print(person.name, 'has', len(list(person.pets)), 'pets.')
In this example, we use the select()
method to create a query that gets all the Person
records where they have at least one Pet
. We then iterate over these people and print out their names and the number of pets they have.
Peewee provides many more features for working with databases, such as transactional support, row-level locking, and a powerful querying language.
Can you use Python for a database?
I'm happy to help!
Python is an excellent choice for working with databases! In fact, it has become the de facto standard for many data-driven applications.
There are several ways to work with databases using Python:
SQLite: SQLite is a self-contained database that doesn't require a separate server process. You can create and manage a SQLite database directly from your Python script using thesqlite3
module. Pandas: Pandas is a popular Python library for data manipulation and analysis. It includes built-in support for various data formats, including CSV, Excel, and SQL databases. SQLAlchemy: SQLAlchemy is an Object-Relational Mapping (ORM) tool that allows you to interact with your database using Python objects rather than raw SQL queries. This makes it easier to work with complex databases. PyODBC or pygresql: If you're working with a specific database management system, such as MySQL or PostgreSQL, you can use the PyODBC
or pygresql
libraries to connect to your database and perform CRUD (Create, Read, Update, Delete) operations.
Some benefits of using Python for databases include:
Ease of use: Python's syntax is clean and intuitive, making it easier to write database-driven applications. Rapid development: With a robust set of libraries and frameworks, you can quickly build and deploy data-driven applications. Scalability: Python can handle large datasets and scale well with the help of distributed computing frameworks like Dask or Spark.Some popular Python libraries for databases include:
Pandas (for data manipulation and analysis) SQLAlchemy (for ORM and database abstraction) PyODBC (for ODBC-based database connections) pygresql (for PostgreSQL-specific database interactions)Overall, Python is a fantastic choice for working with databases!