corycorycory corycorycory - 1 year ago 74
Python Question

Django model where field is based on another field unless specified otherwise

Say I have a django model called Car and another called UserCar which has a related car object.

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)

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

Answer Source

Try using the following:

class UserCar(models.Model):

    ... # your fields here

    # Override the save function here
    def save(self, *args, **kwargs):
        if self.mpg is None:
            self.mpg =
        super(UserCar, self).save(*args, **kwargs)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download