sqlalchemy experiment wip.
This commit is contained in:
parent
775fd1034c
commit
f4d6b766fa
3 changed files with 56 additions and 1 deletions
|
|
@ -24,7 +24,7 @@ class Author(Base):
|
|||
|
||||
|
||||
class Book(Base):
|
||||
__tablename__ = "books"
|
||||
__tablename__: str = "books"
|
||||
|
||||
id: Column[int] = Column(Integer, primary_key=True)
|
||||
title: Column[str] = Column(Text, nullable=False)
|
||||
|
|
|
|||
32
code_to_optimize/book_catalog2.py
Normal file
32
code_to_optimize/book_catalog2.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Any, cast
|
||||
|
||||
from _typeshed import SupportsDunderGT, SupportsDunderLT
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from code_to_optimize.book_catalog import (
|
||||
POSTGRES_CONNECTION_STRING,
|
||||
Author,
|
||||
Base,
|
||||
Book,
|
||||
_session,
|
||||
_t,
|
||||
authors,
|
||||
authors_name,
|
||||
engine,
|
||||
init_table,
|
||||
session_factory,
|
||||
)
|
||||
|
||||
|
||||
def get_authors(session: Session) -> list[Author]:
|
||||
books: list[Book] = session.query(Book).all()
|
||||
_authors: list[Author] = []
|
||||
book: Book
|
||||
for book in books:
|
||||
_authors.append(book.author)
|
||||
return sorted(
|
||||
list(set(_authors)),
|
||||
key=lambda x: cast(SupportsDunderLT[Any] | SupportsDunderGT[Any], x.id),
|
||||
)
|
||||
23
code_to_optimize/book_catalog3.py
Normal file
23
code_to_optimize/book_catalog3.py
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from code_to_optimize.book_catalog import (
|
||||
POSTGRES_CONNECTION_STRING,
|
||||
Author,
|
||||
Base,
|
||||
Book,
|
||||
_session,
|
||||
_t,
|
||||
authors,
|
||||
authors_name,
|
||||
engine,
|
||||
init_table,
|
||||
session_factory,
|
||||
)
|
||||
|
||||
|
||||
def get_authors(session):
|
||||
books = session.query(Book).all()
|
||||
_authors = []
|
||||
for book in books:
|
||||
_authors.append(book.author)
|
||||
return sorted(list(set(_authors)), key=lambda x: x.id)
|
||||
Loading…
Reference in a new issue