0

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)

1 Answer 1

3

There's a Python built-in function specifically for this: setattr.

for key, value in parsedData.items():
  setattr(self, key, value)

for a use like this you wouldn't even have to have key and value defined separately.

for data_item in parsedData.items():
    setattr(self, *data_item)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.