sqlalchemy_nplusone
Detect N+1 query patterns in SQLAlchemy by monitoring lazy loads. Identify relationships that trigger extra queries per row.
Instructions
Relationships SQLAlchemy will load one row at a time.
orders = db.query(Order).all()
for order in orders:
print(order.customer.name) # one query per order
And the quieter FastAPI shape, where there is no loop to see:
@app.get("/orders", response_model=list[OrderOut])
def list_orders(db=Depends(get_db)):
return db.query(Order).all()
OrderOut declares `items`, so serialisation walks the relationship once
per row - after the endpoint has returned, which is why nothing in the
function body mentions it.
nplusone finds this at runtime by watching lazy loads happen, and
lazy="raise" turns it into an exception; both need the code path to run.
A relationship declared lazy="selectin", "joined" or "raise" is never
reported here, since the first two are already eager and the third is the
recommended fix.
Nothing is imported. Needs no Django.
Args:
search_path: directory to scan. Defaults to the configured project.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| search_path | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||