Skip to content

Commit

Permalink
Fixes test, updates release notes
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinger86 committed Oct 23, 2021
1 parent be9553f commit 8fcc3b6
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 53 deletions.
88 changes: 57 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
[![Python versions](https://img.shields.io/pypi/pyversions/django-lifecycle.svg)](https://pypi.org/project/django-lifecycle/)
![PyPI - Django Version](https://img.shields.io/pypi/djversions/django-lifecycle)


This project provides a `@hook` decorator as well as a base model and mixin to add lifecycle hooks to your Django models. Django's built-in approach to offering lifecycle hooks is [Signals](https://docs.djangoproject.com/en/dev/topics/signals/). However, my team often finds that Signals introduce unnecessary indirection and are at odds with Django's "fat models" approach.

**Django Lifecycle Hooks** supports Python 3.5, 3.6, 3.7, 3.8 and 3.9, Django 2.0.x, 2.1.x, 2.2.x, 3.0.x and 3.1.x.
Expand Down Expand Up @@ -35,13 +34,13 @@ Instead of overriding `save` and `__init__` in a clunky way that hurts readabili

```python
# same class and field declarations as above ...

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._orig_contents = self.contents
self._orig_status = self.status


def save(self, *args, **kwargs):
if self.pk is not None and self.contents != self._orig_contents:
self.updated_at = timezone.now()
Expand All @@ -62,81 +61,108 @@ Instead of overriding `save` and `__init__` in a clunky way that hurts readabili

# Changelog

## 0.9.2 (October 2021)

- Run hooked methods inside transactions, just as signals do. Thanks @amirmotlagh!

## 0.9.1 (March 2021)
* Makes hooks work with OneToOneFields. Thanks @bahmdev!

- Makes hooks work with OneToOneFields. Thanks @bahmdev!

## 0.9.0 (February 2021)
* Prevents calling a hooked method twice with the same state. Thanks @garyd203!

- Prevents calling a hooked method twice with the same state. Thanks @garyd203!

## 0.8.1 (January 2021)
* Added missing return to `delete()` method override. Thanks @oaosman84!

- Added missing return to `delete()` method override. Thanks @oaosman84!

## 0.8.0 (October 2020)
* Significant performance improvements. Thanks @dralley!

- Significant performance improvements. Thanks @dralley!

## 0.7.7 (August 2020)
* Fixes issue with `GenericForeignKey`. Thanks @bmbouter!

- Fixes issue with `GenericForeignKey`. Thanks @bmbouter!

## 0.7.6 (May 2020)
* Updates to use constants for hook names; updates docs to indicate Python 3.8/Django 3.x support. Thanks @thejoeejoee!

- Updates to use constants for hook names; updates docs to indicate Python 3.8/Django 3.x support. Thanks @thejoeejoee!

## 0.7.5 (April 2020)
* Adds static typed variables for hook names; thanks @Faisal-Manzer!
* Fixes some typos in docs; thanks @tomdyson and @bmispelon!

- Adds static typed variables for hook names; thanks @Faisal-Manzer!
- Fixes some typos in docs; thanks @tomdyson and @bmispelon!

## 0.7.1 (January 2020)
* Fixes bug in `utils._get_field_names` that could cause recursion bug in some cases.

- Fixes bug in `utils._get_field_names` that could cause recursion bug in some cases.

## 0.7.0 (December 2019)
* Adds `changes_to` condition - thanks @samitnuk! Also some typo fixes in docs.

- Adds `changes_to` condition - thanks @samitnuk! Also some typo fixes in docs.

## 0.6.1 (November 2019)
* Remove variable type annotation for Python 3.5 compatability.

- Remove variable type annotation for Python 3.5 compatability.

## 0.6.0 (October 2019)
* Adds `when_any` hook parameter to watch multiple fields for state changes

- Adds `when_any` hook parameter to watch multiple fields for state changes

## 0.5.0 (September 2019)
* Adds `was_not` condition
* Allow watching changes to FK model field values, not just FK references

- Adds `was_not` condition
- Allow watching changes to FK model field values, not just FK references

## 0.4.2 (July 2019)
* Fixes missing README.md issue that broke install.

- Fixes missing README.md issue that broke install.

## 0.4.1 (June 2019)
* Fixes [urlman](https://github.com/andrewgodwin/urlman)-compatability.

- Fixes [urlman](https://github.com/andrewgodwin/urlman)-compatability.

## 0.4.0 (May 2019)
* Fixes `initial_value(field_name)` behavior - should return value even if no change. Thanks @adamJLev!

- Fixes `initial_value(field_name)` behavior - should return value even if no change. Thanks @adamJLev!

## 0.3.2 (February 2019)
* Fixes bug preventing hooks from firing for custom PKs. Thanks @atugushev!

- Fixes bug preventing hooks from firing for custom PKs. Thanks @atugushev!

## 0.3.1 (August 2018)
* Fixes m2m field bug, in which accessing auto-generated reverse field in `before_create` causes exception b/c PK does not exist yet. Thanks @garyd203!

- Fixes m2m field bug, in which accessing auto-generated reverse field in `before_create` causes exception b/c PK does not exist yet. Thanks @garyd203!

## 0.3.0 (April 2018)
* Resets model's comparison state for hook conditions after `save` called.

- Resets model's comparison state for hook conditions after `save` called.

## 0.2.4 (April 2018)
* Fixed support for adding multiple `@hook` decorators to same method.

- Fixed support for adding multiple `@hook` decorators to same method.

## 0.2.3 (April 2018)
* Removes residual mixin methods from earlier implementation.

- Removes residual mixin methods from earlier implementation.

## 0.2.2 (April 2018)
* Save method now accepts `skip_hooks`, an optional boolean keyword argument that controls whether hooked methods are called.

- Save method now accepts `skip_hooks`, an optional boolean keyword argument that controls whether hooked methods are called.

## 0.2.1 (April 2018)
* Fixed bug in `_potentially_hooked_methods` that caused unwanted side effects by accessing model instance methods decorated with `@cache_property` or `@property`.

- Fixed bug in `_potentially_hooked_methods` that caused unwanted side effects by accessing model instance methods decorated with `@cache_property` or `@property`.

## 0.2.0 (April 2018)
* Added Django 1.8 support. Thanks @jtiai!
* Tox testing added for Python 3.4, 3.5, 3.6 and Django 1.8, 1.11 and 2.0. Thanks @jtiai!

- Added Django 1.8 support. Thanks @jtiai!
- Tox testing added for Python 3.4, 3.5, 3.6 and Django 1.8, 1.11 and 2.0. Thanks @jtiai!

# Testing

Tests are found in a simplified Django project in the ```/tests``` folder. Install the project requirements and do ```./manage.py test``` to run them.
Tests are found in a simplified Django project in the `/tests` folder. Install the project requirements and do `./manage.py test` to run them.

# License

Expand Down
2 changes: 1 addition & 1 deletion django_lifecycle/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from .django_info import IS_GTE_1_POINT_9

__version__ = "0.9.1"
__version__ = "0.9.2"
__author__ = "Robert Singer"
__author_email__ = "[email protected]"

Expand Down
32 changes: 16 additions & 16 deletions django_lifecycle/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ def has_changed(self, field_name: str) -> bool:
return False

def _clear_watched_fk_model_cache(self):
"""
"""
""" """
for watched_field_name in self._watched_fk_models():
field = self._meta.get_field(watched_field_name)

Expand Down Expand Up @@ -172,9 +170,9 @@ def _potentially_hooked_methods(cls):
@lru_cache(typed=True)
def _watched_fk_model_fields(cls) -> List[str]:
"""
Gather up all field names (values in 'when' key) that correspond to
field names on FK-related models. These will be strings that contain
periods.
Gather up all field names (values in 'when' key) that correspond to
field names on FK-related models. These will be strings that contain
periods.
"""
watched = [] # List[str]

Expand All @@ -192,9 +190,9 @@ def _watched_fk_models(cls) -> List[str]:

def _run_hooked_methods(self, hook: str) -> List[str]:
"""
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
Iterate through decorated methods to find those that should be
triggered by the current hook. If conditions exist, check them before
running otherwise go ahead and run.
"""
fired = []

Expand All @@ -210,10 +208,12 @@ def _run_hooked_methods(self, hook: str) -> List[str]:
if not self._check_callback_conditions(when_field, callback_specs):
continue
elif when_any_field:
if not any([
self._check_callback_conditions(field_name, callback_specs)
for field_name in when_any_field
]):
if not any(
[
self._check_callback_conditions(field_name, callback_specs)
for field_name in when_any_field
]
):
continue

# Only call the method once per hook
Expand Down Expand Up @@ -277,9 +277,9 @@ def _check_changes_to_condition(self, field_name: str, specs: dict) -> bool:
@classmethod
def _get_model_property_names(cls) -> List[str]:
"""
Gather up properties and cached_properties which may be methods
that were decorated. Need to inspect class versions b/c doing
getattr on them could cause unwanted side effects.
Gather up properties and cached_properties which may be methods
that were decorated. Need to inspect class versions b/c doing
getattr on them could cause unwanted side effects.
"""
property_names = []

Expand Down
8 changes: 3 additions & 5 deletions tests/testapp/tests/test_user_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def test_email_user_about_name_change(self):

def test_skip_hooks(self):
"""
Hooked method that auto-lowercases email should be skipped.
Hooked method that auto-lowercases email should be skipped.
"""
account = UserAccount.objects.create(**self.stub_data)
account.email = "Homer.Simpson@springfieldnuclear"
Expand All @@ -128,11 +128,9 @@ def test_skip_hooks(self):

def test_delete_should_return_default_django_value(self):
"""
Hooked method that auto-lowercases email should be skipped.
Hooked method that auto-lowercases email should be skipped.
"""
UserAccount.objects.create(**self.stub_data)
value = UserAccount.objects.all().delete()

self.assertEqual(
value, (1, {"testapp.Locale_users": 0, "testapp.UserAccount": 1})
)
self.assertEqual(value, (1, {"testapp.UserAccount": 1}))

0 comments on commit 8fcc3b6

Please sign in to comment.