简体   繁体   English

Django模型未在celery任务中更新

[英]Django model does not update in celery task

I am trying to make a celery task that updates django model and sends email. 我试图做一个芹菜任务,更新Django模型并发送电子邮件。 The emails are sent properly but the model is not saved to the database. 电子邮件已正确发送,但模型未保存到数据库。 Any ideas why does it happen? 任何想法为什么会发生? Here is my sample task: 这是我的示例任务:

@app.task()
def send_invitation(company_id):
    users = User.objects.filter(company_id=company_id, user_email__invitation_sent=False)

    for user in users:
        user.user_email.invitation_sent = True
        user.save()
        send_email(user)

I have tried several saving options for example user.user_email.save() but when the task finishes, mails are sent but invitation_sent stays False and I can't figure out why this happens 我曾尝试例如几个省电选项user.user_email.save()但是当任务完成后,邮件被发送,但invitation_sent停留False ,我想不通为什么会这样

The issue is that you're calling save() on the User model where as you are changing what appears to be the UserEmail (or something like it) model. 问题是您要在用户模型上调用save()在此更改中似乎是UserEmail(或类似形式)的模型。

to fix this properly keep track of which model you want to save, so in your example: 要正确解决此问题,请跟踪要保存的模型,因此在您的示例中:

...
user.user_mail.invitation_sent = True
# call save on user_email instance
user.user_mail.save() #  <---- here 

Though to be fair from your example you should definitely keep track of order of operations done with your emails. 尽管从您的示例中可以看出,您绝对应该跟踪处理电子邮件的操作顺序。 So send the email and if its successful, then mark it as such, don't say you did something before you do it. 因此,发送电子邮件,如果成功,则将其标记为电子邮件,不要说在做之前先做过什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM