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.
This commit is contained in:
parent
53e1859ee8
commit
9d2a4139b7
1 changed files with 15 additions and 20 deletions
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in a new issue