Django signals that fire when specific model fields change
Low maintenance activity. Last release 11 months ago, commits in 0 of the last 26 weeks. Weaker on commit activity and release cadence.
pip install django-fieldsignalsIntroduction
django-fieldsignals simply makes it easy to tell when the fields on your model have changed.
Often model updates are quite expensive. Sometimes the expensive operations are very rare. This makes it tempting to put the update logic in a view, rather than in a save() method or in a signal receiver:
# A bad example. Don't do this!
def edit_poll(request, poll_id):
# ...
if form.cleaned_data['poll_name'] != poll.name:
poll.update_slug(form.cleaned_data['poll_name'])
poll.save()
That's a bad idea, because your model consistency is now dependent on your view.
Instead, use django-fieldsignals:
from django.dispatch import receiver
from fieldsignals import pre_save_changed
@receiver(pre_save_changed, sender=Poll, fields=['name'])
def update_poll_slug(sender, instance, **kwargs):
instance.slug = slugify(instance.name)
In case you want to know what changed, django-fieldsignals even tells you the old and new values of your fields:
@receiver(pre_save_changed, sender=Poll)
def print_all_field_changes(sender, instance, changed_fields, **kwargs):
for field_name, (old, new) in changed_fields.items():
print(f'{field_name} changed from {old} to {new}')
Installation
- This library is on PyPI so you can install it with:
pip install django-fieldsignals
- Add
"fieldsignals"to yourINSTALLED_APPSsetting like this:
INSTALLED_APPS = (
...
'fieldsignals',
)
- Add some signals!
Where should my signals code live?
Field signals must be connected after the django apps are ready. So putting signal connectors at the bottom of your models file, or other random places won't work.
The best place to connect fieldsignals is an AppConfig.ready() handler.
Notes
- fieldsignals signals do not trigger if your fields don't change between instantiation and
save(). That is: