pythondjangocelery

Updating object attribute from database in Django


Let's say I have a model representing a task:

class Task(models.Model):
    on_status = models.BooleanField()

    def run(self):
        if self.on_status:
            # do stuff

I run this task with Celery Beat and I have a dashboard running on Gunicorn both using the same database.

app = Celery("app")

app.conf.beat_schedule = {
    "run_task": {
        "task": "run_tasks",
        "schedule": 5.0,
        "options": {
            "expires": 6.0,
        },
    },
}


tasks = Task.objects.all()


@app.task
def run_tasks():
    for task in tasks:
        task.run()

I can change on_status from my dashboard, but then I need to update self.on_status of the instance inside Celery Beat process. Is there a command to update attribute value from database or is there a different approach?


Solution

  • Regardless of how you are using celery-beat, the core question seems to be how you can refresh a django model object. That is done with refresh_from_db: https://docs.djangoproject.com/en/5.1/ref/models/instances/#refreshing-objects-from-database