[英]Background workers and overriding save method on Django models
我有一個長期運行的過程,它依賴於 model 字段。
假設我有一個看起來像這樣的 model
class Client(models.Model):
input_data = models.CharField(max_length=100)
# The field that will be computed in the background task
computed_data = models.CharField(max_length=100, null=True, blank=True)
我想每次更新這個 model 時觸發一個后台任務,但問題是我還需要在后台任務更新實例后調用 save 方法。
它大致看起來像這樣。
def a_long_running_background_task(instance):
input_data = instance.input_data # Reading the model input data
# Updating the output_data field using the input data from the model instance
instance.output_data = input_data.title()
# To make sure the changes apply to the database we need to call the save method
instance.save()
這段代碼的問題是它會導致無限循環,因為我在save方法上調用了后台任務,而我在后台任務中調用了save方法。
我一直收到這個錯誤
RecursionError: maximum recursion depth exceeded while calling a Python object
在我研究了這個問題之后,我找到了一個解決方案,它建議使用帶有 created 屬性的 post_save 信號,然后檢查實例是否已創建,然后執行任務,如果它剛剛更新,我會跳過它,因為這意味着它正在從后台工作人員調用保存。
信號看起來像這樣:
@receiver(post_save, sender=Client)
def handle_new_client(sender, instance, created, **kwargs):
if created:
a_long_running_task(instance)
現在的問題是,我想要一個更新功能,我希望在更新 model 時觸發后台任務,但它目前僅在創建 object 時觸發。
我想到了一個解決方案,但我不確定如何實現它或者它是否可行,即將計算字段從輸入字段拆分為兩個不同的模型。
非常感謝任何幫助。
一種選擇是使用bulk_update更新后台任務中的實例。 這個 function 不會調用模型的save
方法,不會發出任何信號,消除了任何遞歸問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.