Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
dj-kaos-utils / mixins.py
Size: Mime:
# Credit to ChatGPT for this implementation
class TrackChangesMixin:
    """
    Mixin class that tracks changes made to attributes specified in obj.config.attrs_to_track.
    Example:
        >>> class MyModel(TrackChangesMixin, Model):
        >>>    name = CharField()
        >>>    age = IntegerField()
        >>>
        >>>    config = MyModelConfig(attrs_to_track=['name'])
        >>>
        >>> model = MyModel(name="John", age=30)
        >>> model.name = "Mark"
        >>> model.has_field_changed("name") # True
        >>> model.has_field_changed("age") # False
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__original_values = {}

    def __setattr__(self, name, value):
        """
        Save the original value of the attr if it hasn't been saved yet and attr is in attrs_to_track
        """

        if name in self.config.attrs_to_track:
            # Save the original value of the attr if it hasn't been saved yet
            if name not in self.__original_values:
                try:
                    self.__original_values[name] = getattr(self, name)
                except AttributeError:
                    pass

        super().__setattr__(name, value)

    def has_attr_changed(self, name):
        """
        Check if the attr has changed from its original value
        :param name: name of the attr to check
        :type name: str
        :return: bool indicating whether the attr has changed or not
        """

        if name in self.__original_values:
            # Return whether the attr's value has changed from the original value
            return getattr(self, name) != self.__original_values[name]
        # The attr has not been changed if it doesn't have an original value
        return False

    def get_attr_original_value(self, name):
        return self.__original_values[name]


__all__ = (
    'TrackChangesMixin',
)