Leon
Leon

Reputation: 6554

Save object with Foreign key

models.py:

class Car(models.Model):
    cost = models.PositiveIntegerField()


class Detail(models.Model):
    car = models.ForeignKey(Car, blank=True, null=True,)
    name = models.CharField()
    price = models.PositiveIntegerField()

    def save(self, *args, **kwargs):

        if self.car:
            self.car.cost += self.price

        super(Detail, self).save(*args, **kwargs)

The logic is: when we add a new detail to car, for example, engine (cost $5000), we need to up price of the car (car.cost + 5000)

Everything fine, but cost of car does not updates.

How to fix that?

Thanks!

Upvotes: 0

Views: 31

Answers (1)

Mihai Zamfir
Mihai Zamfir

Reputation: 2166

self.care.save() after updateing cost

Upvotes: 1

Related Questions