perf(printer): remove deferred-field N+1 and scope Printer to real printers

The printer chart API was issuing one extra SELECT per row per field that the
serializer read but .only() omitted. nozzle_temp_left/nozzle_target_temp_left
were added to the serialization loop without being added to _METRICS_API_FIELDS,
so a single-day request ran 5,507 queries and took 34s; the UI's default 48h
range took 87s. Against a remote Postgres this is pure round-trip latency.

- Add the two left-nozzle fields to _METRICS_API_FIELDS.
- Always apply both time bounds in PrinterDataAPIView. Missing or partial date
  params previously left the range open, so a bare API call scanned the whole
  metrics table.
- Give PrinterDashboardView the same treatment the API already had: .only(),
  sampling to _MAX_CHART_POINTS, and a targeted snapshot fetch. It also
  evaluated its queryset twice, because .last() on an unevaluated queryset
  issues its own query plus its own prefetch.
- Extract sample_metrics() and fetch_snapshots_by_metric() for reuse.

Printer shares the infrastructure_device table with a host project's other
devices and had no category field, so Printer.objects.filter(is_active=True)
could return a NAS. Add a category field and a category-scoped default manager,
keeping all_objects as the unfiltered base manager so related descriptors still
resolve every row. Migration 0009 creates the column in standalone deployments
and skips the DDL where the host project already owns it.

Measured: API 87s -> 0.67s, dashboard 3.4s -> 0.9s. Query counts are now
independent of row count, asserted by tests.
This commit is contained in:
RNL
2026-07-28 00:03:08 +10:00
parent 86619a807c
commit 6f19560842
6 changed files with 504 additions and 44 deletions

View File

@@ -0,0 +1,77 @@
"""Add Printer.category so printer queries can be scoped away from other devices.
`infrastructure_device` is shared with host projects. In a standalone Bambu-Run
deployment bambu_run owns the table and the column must be created here. In a
host project like RAE the table was created by that project's own app and
already carries a `category` column, so creating it again would fail.
`AddFieldIfMissing` introspects the table and only emits DDL when needed; the
model state is updated either way.
"""
import django.db.models.manager
from django.db import migrations, models
class AddFieldIfMissing(migrations.AddField):
"""AddField that is a no-op at the database level if the column exists."""
def database_forwards(self, app_label, schema_editor, from_state, to_state):
model = to_state.apps.get_model(app_label, self.model_name)
with schema_editor.connection.cursor() as cursor:
existing = {
column.name
for column in schema_editor.connection.introspection.get_table_description(
cursor, model._meta.db_table
)
}
if self.name in existing:
return
super().database_forwards(app_label, schema_editor, from_state, to_state)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
"""Reverse the model state only, never the column.
In a host project the column belongs to that project's own app — dropping
it on reverse would break the host's device model. Leaving an unused
column behind in a standalone rollback is the harmless side of this trade.
"""
return
class Migration(migrations.Migration):
dependencies = [
("bambu_run", "0008_printermetrics_nozzle_info"),
]
operations = [
AddFieldIfMissing(
model_name="printer",
name="category",
field=models.CharField(
default="threed_printer",
help_text=(
"Device category. Always 'threed_printer' for printers — present "
"because host projects may share this table with other device types."
),
max_length=50,
),
),
migrations.AlterModelOptions(
name="printer",
options={
"base_manager_name": "all_objects",
"default_manager_name": "objects",
"ordering": ["name"],
"verbose_name": "Printer",
"verbose_name_plural": "Printers",
},
),
migrations.AlterModelManagers(
name="printer",
managers=[
("all_objects", django.db.models.manager.Manager()),
("objects", django.db.models.manager.Manager()),
],
),
]