2026-05-05 01:32:27 +03:30
|
|
|
from django.db import migrations, models
|
|
|
|
|
|
|
|
|
|
|
2026-05-05 21:01:58 +03:30
|
|
|
def ensure_device_catalogs_m2m_table(apps, schema_editor):
|
|
|
|
|
FarmDevice = apps.get_model("device_hub", "FarmDevice")
|
|
|
|
|
through_model = FarmDevice._meta.get_field("device_catalogs").remote_field.through
|
|
|
|
|
existing_tables = set(schema_editor.connection.introspection.table_names())
|
|
|
|
|
if through_model._meta.db_table not in existing_tables:
|
|
|
|
|
schema_editor.create_model(through_model)
|
|
|
|
|
|
|
|
|
|
|
2026-05-05 01:32:27 +03:30
|
|
|
def copy_sensor_catalog_to_device_catalogs(apps, schema_editor):
|
|
|
|
|
FarmDevice = apps.get_model("device_hub", "FarmDevice")
|
2026-05-05 21:01:58 +03:30
|
|
|
through_model = FarmDevice._meta.get_field("device_catalogs").remote_field.through
|
|
|
|
|
through_table = through_model._meta.db_table
|
|
|
|
|
farm_device_column = through_model._meta.get_field("farmdevice").column
|
|
|
|
|
device_catalog_column = through_model._meta.get_field("devicecatalog").column
|
|
|
|
|
|
|
|
|
|
with schema_editor.connection.cursor() as cursor:
|
|
|
|
|
for farm_device_id, sensor_catalog_id in FarmDevice.objects.exclude(sensor_catalog__isnull=True).values_list("pk", "sensor_catalog_id").iterator():
|
|
|
|
|
cursor.execute(
|
|
|
|
|
f"""
|
|
|
|
|
INSERT IGNORE INTO {schema_editor.quote_name(through_table)}
|
|
|
|
|
({schema_editor.quote_name(farm_device_column)}, {schema_editor.quote_name(device_catalog_column)})
|
|
|
|
|
VALUES (%s, %s)
|
|
|
|
|
""",
|
|
|
|
|
[farm_device_id, sensor_catalog_id],
|
|
|
|
|
)
|
2026-05-05 01:32:27 +03:30
|
|
|
|
|
|
|
|
|
|
|
|
|
class Migration(migrations.Migration):
|
2026-05-05 21:01:58 +03:30
|
|
|
atomic = False
|
2026-05-05 01:32:27 +03:30
|
|
|
|
|
|
|
|
dependencies = [
|
|
|
|
|
("device_hub", "0007_devicecatalog_dynamic_fields"),
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
operations = [
|
2026-05-05 21:01:58 +03:30
|
|
|
migrations.SeparateDatabaseAndState(
|
|
|
|
|
database_operations=[],
|
|
|
|
|
state_operations=[
|
|
|
|
|
migrations.AddField(
|
|
|
|
|
model_name="farmdevice",
|
|
|
|
|
name="device_catalogs",
|
|
|
|
|
field=models.ManyToManyField(blank=True, related_name="composite_farm_devices", to="device_hub.devicecatalog"),
|
|
|
|
|
),
|
|
|
|
|
],
|
2026-05-05 01:32:27 +03:30
|
|
|
),
|
2026-05-05 21:01:58 +03:30
|
|
|
migrations.RunPython(ensure_device_catalogs_m2m_table, migrations.RunPython.noop),
|
2026-05-05 01:32:27 +03:30
|
|
|
migrations.RunPython(copy_sensor_catalog_to_device_catalogs, migrations.RunPython.noop),
|
|
|
|
|
]
|