aldeano aldeano - 2 months ago 14
Python Question

Saving data in a inherited django model

I'm building an app to save data and some calculations made with that data, the idea is keep the data in one model and the calculations in other. So, the models are like this:

class FreshData(models.Model):
name = models.CharField(max_length=20)
one = models.IntegerField()
two = models.IntegerField()

def save(self, *args, **kwargs):
Calculations()
Calculations.three = self.one + self.two
super(FreshData, self).save(*args, **kwargs)
Calculations.save()

class Calculations(FreshData):
three = models.IntegerField()


I've got a
ValueError
complaining that "self.one" and "self.two" are without values. I believe my design is flawed/wrong and django has a better/simpler way to store related data.

Answer

You have just instantiated a class but not stored calculations() in a variable, plus give your class names capital letters. Also your super call is incorrect, it needs to reference your model and not Blog.

The reason self.one probably doesn't have a value is because you are doing the work before the call to the super save call. So instead do your work after saving "your self".

class FreshData(models.Model):
    name = models.CharField(max_length=20)
    one = models.IntegerField()
    two = models.IntegerField()

    def save(self, *args, **kwargs):
        super(FreshData, self).save(*args, **kwargs)
        calculations = Calculations()
        calculations.three = self.one + self.two
        calculations.save()

class Calculations(FreshData):
    three = models.IntegerField()

Besides that I am not sure why you need to extend from FreshData in your example Calculations would inherit the name, one and two fields from FreshData. If you wanted to store the calculations only in a separate model then just store a reference back to the original data like so:

class Calculations(models.Model):
    fresh_data = models.ForeignKey(FreshData)
    three = models.IntegerField()

Then just make sure to pass in fresh_data when instantiating your Calculations:

def save(self, *args, **kwargs):
    super(FreshData, self).save(*args, **kwargs)
    calculations = Calculationrs(fresh_data=self)
    ...