Reputation: 1656
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
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