Replace the legacy Session.query() API #17

Merged
alexander merged 11 commits from sqlalchemy-select into develop 2026-12-02 00:38:24 +01:00
Showing only changes of commit 9d2a4139b7 - Show all commits

Query with select() in City

`Session.query()` is the legacy API in SQLAlchemy 2.x.

The addresses with restaurants are now selected with a subquery in one statement.
Alexander Hess 2026-12-01 23:34:52 +01:00
Signed by: alexander
GPG key ID: B46EDB4DFC26805D

View file

@ -163,29 +163,25 @@ class City(meta.Base):
`.map` for convenience in interactive usage
"""
# Obtain all primary `Address`es in the city that host `Restaurant`s.
addresses = (
db.session.query(db.Address)
.filter(
addresses = db.session.scalars(
sa.select(db.Address).where(
db.Address.id.in_(
db.session.query(db.Address.primary_id)
sa.select(db.Address.primary_id)
.join(db.Restaurant, db.Address.id == db.Restaurant.address_id)
.filter(db.Address.city == self)
.distinct()
.all(),
.where(db.Address.city == self)
.distinct(),
),
)
.all()
)
),
).all()
for address in addresses:
# Show the restaurant's name if there is only one.
# Otherwise, list all the restaurants' ID's.
restaurants = (
db.session.query(db.Restaurant)
restaurants = db.session.scalars(
sa.select(db.Restaurant)
.join(db.Address, db.Restaurant.address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.all()
)
.where(db.Address.primary_id == address.id),
).all()
if len(restaurants) == 1:
tooltip = f"{restaurants[0].name} (#{restaurants[0].id})"
else:
@ -195,12 +191,11 @@ class City(meta.Base):
if order_counts:
# Calculate the number of orders for ALL restaurants ...
n_orders = (
db.session.query(db.Order.id)
n_orders = db.session.execute(
sa.select(sa.func.count(db.Order.id))
.join(db.Address, db.Order.pickup_address_id == db.Address.id)
.filter(db.Address.primary_id == address.id)
.count()
)
.where(db.Address.primary_id == address.id),
).scalar_one()
# ... and adjust the size of the red dot on the `.map`.
if n_orders >= 1000:
radius = 20