[英]Can I trigger Celery task on table update in Django?
例如,我有一个 model:
class SomeModel(model.Model):
is_active = BooleanField(default=False)
...
当 is_active 更改为 True 时,是否可以触发 Celery 任务? 这里最重要的是,无论 is_active 以何种方式更改,无论是通过 shell、管理面板、api 调用等更改,我都需要触发它。我使用的数据库是 psql。
您可以为此使用信号。 一个棘手的部分是确定您的字段在此过程中实际发生了变化。 在这种情况下,您应该调用 refresh_from_db 来比较 pre_save 中的值。 这有点乱但有效
会是这样
@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
另一种方法是使用单独的库,例如https://github.com/rsinger86/django-lifecycle
在您的情况下,您可以通过这种方式创建一个钩子
@hook(AFTER_UPDATE, when="is_active", has_changed=True)
def on_active_change(self):
# send celery task here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.