Django custom save mixin

I've created a custom save function which has some specific logic depending on whether a Django model field has changed or not. Basically, I initialize and store the fields I'm interested in as part of the models init method, and then check whether those fields have changed as part of the models save function.

All works well. But I'd like to create this as a mixin. I'm not sure how to best pass the initialized parameters within the mixin. Any advice?

This works fine:

class Model(models.Model):
    field = models.CharField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.__field_stored = self.field


    def save(self, *args, **kwargs):
        if self.field != self.__field_stored:
            # do something
    
        super().save(*args, **kwargs)
    
    

But as a mixin? The below doesn't seem to work, raising an attribute error:

class Model(SaveMixin, models.Model):
    field = models.CharField()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.__field_stored = self.field

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



class SaveMixin(models.Model):
    field: str
    __field_stored: str

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if self.field != self.__field_stored:
            # do something
    
        super().save(*args, **kwargs)

For anyone interested -- The above mixin actually works fine. Just needed to avoid declaring private variables such as __field_stored.

Back to Top