0

Having these kind of model definitions and a relationship between the two:

class Car(models.Model):
    description = models.CharField(max_length=35)

    def save(self, **kwargs):
        invalidate_cache()
        super().save(**kwargs)

    def delete(self, **kwargs):
        invalidate_cache()
        return super().delete(**kwargs)


class Passenger(models.Model):
    car = models.ForeignKey(Car, related_name='passengers')

I have defined custom save and delete on the Car model because when a car instance is modified I have to perform some extra operations, in particular I need to invalidate a cache.

My doubt is: creating/updating/deleting a related model would call these custom methods?

I'll try to be more clear:

c1 = Car(description='super fast car')
p = Passenger(car=c1)

Clearly the creation of the c1 calls the Car.save but would the creation of the instance p of Passenger call the Car.save or not?

From my tests it seems so but I want to be more sure it wasn't just a specific case and this happens all the time in the Django model handling cycle (I could not find a specific documentation on this).

Leonardo
  • 4,046
  • 5
  • 44
  • 85
  • No, it will only call the `.save(..)` of that object. Furthermore there are ways to *update* models that bypass the `.save(..)` function, therefore performing these tasks is typically *not* a good idea. – Willem Van Onsem Jun 19 '18 at 09:59
  • You can use Django *signals*, but again, there are ways to bypass these signals. For example with `Car.objects.all().update(description='1')`. – Willem Van Onsem Jun 19 '18 at 09:59
  • @WillemVanOnsem what are those ways that bypass the save function? Any update that doesn't call the save it's not reflected in the db or am I mistaken? – Leonardo Jun 19 '18 at 10:05
  • well the one above for example. You do *not* call `.save(..)` but the database *is* updated. So that means that if you enforce invariants with `.save(..)` this can go wrong. – Willem Van Onsem Jun 19 '18 at 10:06

0 Answers0