Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Updating to DB | SQLAlchemy
Databases in Python

book
Updating to DB

In this chapter, we’ll learn how to update records in a database using SQLAlchemy. Updating records is crucial when modifying existing data in your tables, such as changing descriptions or other fields. SQLAlchemy provides efficient and straightforward methods for performing updates.

Updating a Single Record

The most common update operation is modifying a single record. To do this, you need to fetch the object, update its attributes, and then save the changes.

python
product = session.query(Product).filter(Product.id == 1).first()

if product:
product.description = "Updated description for high-end gaming laptop"
session.commit()

To retrieve a product by its ID, you use a query with a filter to specify the desired ID. After updating the product's description, calling session.commit() saves the changes to the database.

Updating Multiple Records

Sometimes, you need to update multiple records at once. SQLAlchemy allows you to use filter() with the update() method to modify records efficiently.

python
session.query(Product).filter(Product.price > 1000).update(
{Product.description: "Updated description for premium products"},
synchronize_session="fetch"
)
session.commit()

To filter products priced above $1000, you use a query with a condition on the price. The update method applies the desired changes to all matching records, while the synchronize_session="fetch" argument ensures the session remains synchronized after the update.

Bulk Updates

For large-scale changes, bulk updates are more efficient as they directly modify database records without loading objects into memory. This makes them ideal for updating many rows at once.

python
session.query(Product).filter(Product.price < 500).update(
{Product.description: "Generic description for affordable products"},
synchronize_session="fetch"
)
session.commit()

This code efficiently updates the description for all products priced below $500 in a single operation. Bulk updates are faster and conserve memory compared to updating records individually.

Завдання

Swipe to start coding

  1. Retrieve all products from the database.
  2. Calculate the new price for each product by reducing it by 20%.
  3. Save the updated prices to the database.

Рішення

from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.orm import declarative_base, sessionmaker

# Initialize the database
engine = create_engine("sqlite:///data.db")
Base = declarative_base()

# Define the Product model
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
description = Column(String)
price = Column(Integer, nullable=False)
is_in_stock = Column(Boolean, default=True)

# Create tables
Base.metadata.create_all(engine)

# Set up the session
Session = sessionmaker(bind=engine)
session = Session()

# Add multiple products (one at a time)
products_to_add = [
{"name": "Laptop", "description": "High-end gaming laptop", "price": 1500},
{"name": "Smartphone", "description": "Latest model smartphone", "price": 800},
{"name": "Headphones", "description": "Noise-cancelling headphones", "price": 200}
]

# Iterate through the list and add each product one by one
for product in products_to_add:
new_product = Product(**product) # Unpack the dictionary as keyword arguments
session.add(new_product)
session.commit() # Commit after adding each product

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 7
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.orm import declarative_base, sessionmaker

# Initialize the database
engine = create_engine("sqlite:///data.db")
Base = declarative_base()

# Define the Product model
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
description = Column(String)
price = Column(Integer, nullable=False)
is_in_stock = Column(Boolean, default=True)

# Create tables
Base.metadata.create_all(engine)

# Set up the session
Session = sessionmaker(bind=engine)
session = Session()

# Add multiple products (one at a time)
products_to_add = [
{"name": "Laptop", "description": "High-end gaming laptop", "price": 1500},
{"name": "Smartphone", "description": "Latest model smartphone", "price": 800},
{"name": "Headphones", "description": "Noise-cancelling headphones", "price": 200}
]

# Iterate through the list and add each product one by one
for product in products_to_add:
new_product = Product(**product) # Unpack the dictionary as keyword arguments
session.add(new_product)
session.commit() # Commit after adding each product

# Update prices by reducing them by 20%
products_to_update = session.query(___).all()

for product in products_to_update:
old_price = ___.price
product.price = int(___.___ * 0.8) # Reduce price by 20%
session.commit() # Commit the change after updating the price
print(f"Updated price for {product.name}: {old_price} -> {product.price}")
toggle bottom row
some-alt