Django model where field is based on another field unless specified otherwise
<p>Say I have a django model called <strong>Car</strong> and another called <strong>UserCar</strong> which has a related car object.</p>

<pre><code>class Car(models.Model):
    name = models.CharField(max_length=100)
    mpg = models.DecimalField(max_digits=6, decimal_places=2, null=True)

class UserCar(models.Model):
    car = models.ForeignKey('Car')
    mpg = models.DecimalField(max_digits=6, decimal_places=2, null=True)
</code></pre>

<p>I would like to override the save function on <strong>UserCar</strong> such that <em>if no value for mpg is specified</em>, the model instance is pre-populated with the value of mpg on the related Car object.</p>

<p>Try using the following:</p>

<pre><code>class UserCar(models.Model):

    ... # your fields here


    # Override the save function here
    def save(self, *args, **kwargs):
        if self.mpg is None:
            self.mpg = self.car.mpg
        super(UserCar, self).save(*args, **kwargs)
</code></pre>

python django django-models