import os import django import sys from django.db import transaction # Ensure the correct working directory sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'django_project'))) # Set up Django environment os.environ.setdefault("DJANGO_SETTINGS_MODULE", "IoTPreTester.settings") django.setup() from IoTAnalyzer.models import Manufacturer, DeviceType, Product, Device def populate_database(): """Populates the database with device types, manufacturers, and a sample device.""" print("Populating database...") # Define device types device_types = [ "Camera", "Smart Plug", "Smart Bulb", "Smart Switch", "Robot Vacuum Cleaner", "Smart Lock", "Smart Controller", "Sensor", ] # Define manufacturers manufacturers = [ "Dreame", "Roborock", "Shelly", "Sonoff", "Dji", "TP link", "Philips Hue", "Nuki", "Ikea", "Xsense", "Aquara", ] # Populate device types with transaction.atomic(): for dt in device_types: obj, created = DeviceType.objects.get_or_create(device_type=dt) if created: print(f"Created DeviceType: {obj.device_type}") else: print(f"DeviceType '{dt}' already exists") # Populate manufacturers with transaction.atomic(): for mf in manufacturers: obj, created = Manufacturer.objects.get_or_create(name=mf) if created: print(f"Created Manufacturer: {obj.name}") else: print(f"Manufacturer '{mf}' already exists") # Create a sample product and device with transaction.atomic(): sample_manufacturer = Manufacturer.objects.filter(name="Shelly").first() sample_device_type = DeviceType.objects.filter(device_type="Smart Controller").first() if sample_manufacturer and sample_device_type: sample_product, created = Product.objects.get_or_create( manufacturer=sample_manufacturer, device_type=sample_device_type, product_name="1PM Gen3" ) if created: print(f"Created Sample Product: {sample_product.product_name}") else: print(f"Sample Product '{sample_product.product_name}' already exists") sample_device, created = Device.objects.get_or_create( product=sample_product, serial="SN123456789", comment="Test device for IoT system" ) if created: print(f"Created Sample Device with Serial: {sample_device.serial}") else: print(f"Sample Device '{sample_device.serial}' already exists") else: print("Error: Could not find required Manufacturer or DeviceType for sample device.") if __name__ == "__main__": populate_database()