简体   繁体   中英

Django model does not update in celery task

I am trying to make a celery task that updates django model and sends email. 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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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