How to create new database table looping through another model in Django
I have a Thermocouple model and I want to create a different model to record Temperatures for each Thermocouple created and save it to database. for thermocouple
| Id | name |
| 1 | thermocouple_1 |
| 2 | thermocouple_2 |
| 3 | thermocouple_3 |
then TemperatureRecord should be as
| id | date | time | user | thermocouple_1 | thermocouple_2 | thermocouple_3 |
| 1 | March 5, 2024 | 2:48 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 |
| 2 | March 5, 2024 | 2:52 p.m. | 2 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 |
| 3 | March 5, 2024 | 2:55 p.m. | 1 | Tempe_value_1 | Tempe_value_2 | Tempe_value_3 |
Thermocouple model
class Thermocouple(models.Model):
name = models.CharField(max_length=50, unique=True, help_text="Name of the thermocouple")
def __str__(self):
return f"{self.name}"
class Meta:
ordering = ['id']
@classmethod
def bulk_create_from_import(cls, data):
cls.objects.bulk_create([cls(**item) for item in data])
and i want to create a different database table model named TemperatureRecord consisting id,user,date,time and Thermocouple items. if created 10 thermocouple, need to be 10 column for each Thermocouple to record temperatures (IntegerField)
I tried using the following code but didn't work.
class TemperatureRecord(models.Model):
date = models.DateField()
time = models.TimeField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __init__(self, *args, **kwargs):
super(TemperatureRecord, self).__init__(*args, **kwargs)
temperatures = Thermocouple.objects.all()
for thermocouple in temperatures:
field_name = thermocouple.name.lower().replace(" ", "_") # Creating field name from thermocouple temperature
setattr(self, field_name, models.IntegerField(null=True, blank=True))
It worked after applying the following code in models.py file:
class TemperatureRecord(models.Model):
user = models.ForeignKey(User, null=True, default='1', on_delete=models.SET_NULL)
date = models.DateField(help_text="Date of the temperature record")
time = models.TimeField(help_text="Time of the temperature record")
class Meta:
verbose_name = "Temperature Record"
verbose_name_plural = "Temperature Records"
def __str__(self):
return f"{self.thermocouple.name} - {self.date} {self.time} - {self.temperature}°C"
class Meta:
ordering = ['id']
@classmethod
def bulk_create_from_import(cls, data):
cls.objects.bulk_create([cls(**item) for item in data])
def create_temperature_field(name):
return models.IntegerField(null=True, blank=True, verbose_name=name)
# Dynamically create fields for each thermocouple
thermocouples = Thermocouple.objects.all()
for thermocouple in thermocouples:
field_name = thermocouple.name.lower().replace(" ", "_")
TemperatureRecord.add_to_class(field_name, create_temperature_field(thermocouple.name))
admin.py
from django.contrib import admin
from .models import Thermocouple, TemperatureRecord
class TemperatureRecordAdmin(admin.ModelAdmin):
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
thermocouples = Thermocouple.objects.all()
for thermocouple in thermocouples:
field_name = thermocouple.name.lower().replace(" ", "_")
form.base_fields[field_name] = forms.IntegerField(required=False)
return form
list_display = ['date', 'time', 'user'] # Add other fields as needed
admin.site.register(TemperatureRecord, TemperatureRecordAdmin)