Good afternoon everyone. I have created a model in Django (code below) and I overwrite the save method to populate the fields. Inside the save methods I call a parser function which returns me a dict where the key is the name of the field in the model, and value, well is the value i'd like to write. The commented lines are working great (such as self.temp = parsedData['temp']) but I would like to refactor it. I thought of something like this but it's not working and I can't figure out why:
for key, value in parsedData.items():
self.key = value
Any ideas ? Thank you very much for your help :)
class Data(models.Model):
deviceId = models.ForeignKey('Device', to_field='deviceId', on_delete=models.CASCADE)
rawData = models.CharField(max_length=24, blank=False, null=False)
temp = models.DecimalField(max_digits=4, decimal_places=2, default=0)
humidity = models.PositiveSmallIntegerField(default=0)
pressure = models.DecimalField(max_digits=8, decimal_places=2, default=0)
luminosity = models.PositiveSmallIntegerField(default=0)
batteryLevel = models.PositiveSmallIntegerField(default=0)
time = models.DateTimeField(null=False, default=now)
def save(self, *args, **kwargs):
"""
Use the parser utility functions in utils to decode the payload
"""
firmware = Device.objects.get(deviceId=self.deviceId).firmware
parsedData = parser(self.rawData, firmware)
# Commented lignes below are working just fine
# self.temp = parsedData['temp']
# self.humidity = parsedData['humidity']
# self.pressure = parsedData['pressure']
# self.luminosity = parsedData['luminosity']
# self.batteryLevel = parsedData['batteryLevel']
# How I would like to refacto the lines above
for key, value in parsedData.items():
self.key = value
super(Data, self).save(*args, **kwargs)