# Generated by Django 4.2.15 on 2024-11-11 21:43

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ("sensors", "0002_alter_sensor_data_label_alter_sensor_data_prefix_and_more"),
    ]

    def populate_sensor_last_value(apps, schema_editor):
        Sensor = apps.get_model("sensors", "Sensor")
        SensorData = apps.get_model("sensors", "SensorData")
        for sensor in Sensor.objects.all():
            try:
                last_data_point = SensorData.objects.filter(sensor=sensor).latest("created_date")
                if last_data_point:
                    sensor.last_value = last_data_point.value
                    sensor.last_read = last_data_point.created_date
                    sensor.save(update_fields=["last_value", "last_read"])
            except:
                pass

    def populate_sensor_last_value_reverse(apps, schema_editor):
        pass

    operations = [
        migrations.AlterModelOptions(
            name="sensor",
            options={"ordering": ["name"]},
        ),
        migrations.AddField(
            model_name="sensor",
            name="last_read",
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name="sensor",
            name="last_value",
            field=models.FloatField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name="sensordata",
            name="created_date",
            field=models.DateTimeField(auto_now_add=True, db_index=True),
        ),
        migrations.RunPython(populate_sensor_last_value, populate_sensor_last_value_reverse),
    ]
