-
Notifications
You must be signed in to change notification settings - Fork 3
the task #4 from HW #4 was completed #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Dmitriy-Klv
wants to merge
1
commit into
samodurOFF:master
Choose a base branch
from
Dmitriy-Klv:feat/SQLAlchemy-task-4
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| import logging | ||
|
|
||
| from sqlalchemy import ( | ||
| DECIMAL, | ||
| Boolean, | ||
| Column, | ||
| Float, | ||
| ForeignKey, | ||
| Integer, | ||
| Numeric, | ||
| String, | ||
| Table, | ||
| create_engine, | ||
| func, | ||
| ) | ||
| from sqlalchemy.orm import DeclarativeBase, declarative_base, relationship, sessionmaker | ||
|
|
||
| logging.basicConfig(level=logging.INFO) | ||
| logger = logging.getLogger("sqlalchemy.engine") | ||
| logger.setLevel(logging.INFO) | ||
|
|
||
| Base = declarative_base() | ||
| engine = create_engine("sqlite:///hm4.db") | ||
|
|
||
|
|
||
| class Category(Base): | ||
| __tablename__ = "categories" | ||
| id = Column(Integer, primary_key=True) | ||
| name = Column(String(50)) | ||
| description = Column(String(100)) | ||
| in_stock = Column(Boolean, default=True) | ||
| products = relationship("Product", back_populates="category") | ||
|
|
||
|
|
||
| class Product(Base): | ||
| __tablename__ = "products" | ||
| id = Column(Integer, primary_key=True) | ||
| name = Column(String(100), nullable=False) | ||
| price = Column(Numeric(precision=10, scale=2)) | ||
| in_stock = Column(Boolean, default=True) | ||
| category_id = Column(Integer, ForeignKey("categories.id")) | ||
| category = relationship("Category", back_populates="products") | ||
|
|
||
|
|
||
| Base.metadata.drop_all(engine) | ||
| Base.metadata.create_all(engine) | ||
| Session = sessionmaker(bind=engine) | ||
|
|
||
| with Session() as session: | ||
| with session.begin(): | ||
| electronics = Category(name="Electronics", description="Gadgets and devices.") | ||
| books = Category(name="Books", description="Printed and electronic books.") | ||
| clothing = Category(name="Clothing", description="Clothing for men and women.") | ||
| session.add_all([electronics, books, clothing]) | ||
| session.commit() | ||
|
|
||
| products = [ | ||
| Product(name="Smartphone", price=299.99, category=electronics), | ||
| Product(name="Laptop", price=499.99, category=electronics), | ||
| Product(name="Sci-Fi Novel", price=15.99, category=books), | ||
| Product(name="Jeans", price=40.50, category=clothing), | ||
| Product(name="T-shirt", price=20.00, category=clothing), | ||
| ] | ||
| session.add_all(products) | ||
| session.commit() | ||
|
|
||
| with Session() as session: | ||
| all_categories = session.query(Category).all() | ||
|
|
||
| for category in all_categories: | ||
| print(f"\nCategory: {category.name}") | ||
| print(f"Description: {category.description}") | ||
| if category.products: | ||
| for product in category.products: | ||
| print(f"Product: {product.name:<25} | Price: {product.price:>8.2f}") | ||
| else: | ||
| print(" (No products found in this category)") | ||
|
|
||
|
|
||
| with Session() as session: | ||
| target_product = session.query(Product).filter(Product.name == "Smartphone").first() | ||
| if target_product: | ||
| target_product.price = 349.99 | ||
| session.commit() | ||
| print(f"Successfully updated price for: {target_product.name}") | ||
| else: | ||
| print("Product 'Smartphone' not found.") | ||
|
|
||
|
|
||
| with Session() as session: | ||
| results = ( | ||
| session.query(Product.category_id, func.count(Product.id)) | ||
| .group_by(Product.category_id) | ||
| .all() | ||
| ) | ||
| for cat_id, count in results: | ||
| print(f"Category ID: {cat_id} | Total Products: {count}") | ||
|
|
||
|
|
||
| with Session() as session: | ||
| results = ( | ||
| session.query(Product.category_id, func.count(Product.id)) | ||
| .group_by(Product.category_id) | ||
| .having(func.count(Product.id) > 1) | ||
| .all() | ||
| ) | ||
|
|
||
| print("\n--- Task 5: Categories with > 1 product ---") | ||
| for cat_id, count in results: | ||
| print(f"Category ID: {cat_id} | Total Products: {count}") | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
У вас выходит проблема N+1. Потому что вы извлекаете связанные объекты множеством запросов в цикле. Лучше сделать 1 большой запрос
Либо тоже через join, но уже по конкретным полям и таблица с Product будет слева