Home > Enterprise >  Can I trigger Celery task on table update in Django?
Can I trigger Celery task on table update in Django?

Time:01-27

For example, I have a model:

class SomeModel(model.Model):
    is_active = BooleanField(default=False)
    ...

Is it possible to trigger Celery task when is_active changes to True? The most important thing here is that I need to trigger it regardless of way is_active changed, whether it changed via shell, admin panel, api call etc. The DB I use is psql.

CodePudding user response:

You can use signals for that. A tricky part is determining that your field actually changed in the process. In that case you should make a refresh_from_db call to compare values in pre_save. It's kind of messy but works

it will be like this

@receiver(pre_save, sender=SomeModel)
def access_rule_card_pre_save(sender, instance: SomeModel, *args, **kwargs):
    old = copy.copy(instance).refresh_from_db()
    changed = instance.is_active != old.is_active
    # you can send task here, or save changed to instance._changed and work with it in post_save

Another approach is using separate library, like https://github.com/rsinger86/django-lifecycle

In your case you can create a hook that way

@hook(AFTER_UPDATE, when="is_active", has_changed=True)
def on_active_change(self):
    # send celery task here
  •  Tags:  
  • Related