corycorycory
corycorycory

Reputation: 1656

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.

Upvotes: 2

Views: 105

Answers (1)

NS0
NS0

Reputation: 6106

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 = self.car.mpg
        super(UserCar, self).save(*args, **kwargs)

Upvotes: 3

Related Questions