Avoid recursive save() when using celery to update Django model fields

后端 未结 1 1214
醉酒成梦
醉酒成梦 2021-02-08 01:26

I\'m overriding a model\'s save() method to call an asynchronous task with Celery. That task also saves the model, and so I end up with a recursive situation where the Celery ta

1条回答
  •  隐瞒了意图╮
    2021-02-08 02:05

    Add a keyword argument that tells save not to recurse:

     def save(self, elevation_data=True, *args, **kwargs):
       super(Route, self).save(*args, **kwargs)
       if elevation_data:
         from .tasks import get_elevation_data
         get_elevation_data.delay(self)
    

    And then:

     from celery.decorators import task
    
     @task()
     def get_elevation_data(route):
         ...
         route.elevation_data = results
         route.save(elevation_data=False)
    

    0 讨论(0)
提交回复
热议问题