Refrehing the Django model after save and 5 second sleep get me old state, what's wrong?

I was able to save the data to a Django model without any errors, but data not reflected in db. But after a sleep time I was able to save the data again with same method. What might be causing this ?

I suspect use of the Google API, but was able to print the data before performing the save operation.

def update_channel():
    client = Client.objects.get(name="name")
    print(f"Existing channel: {data['id']}")             # 123

    # fetch channel data from google api
    data = google_drive.subscribe_new_channel()

    client.channel_id = data["id"]
    client.channel_resource_id = data["resourceId"]
    client.save()

    client.refresh_from_db()
    print(f"New channel: {data['id']}")                  # 456 
    print(f"New channel in db: {client.channel_id}")     # 456

    time.sleep(5)
    client.refresh_from_db()                         
    print(f"channel in db: {client.channel_id}") # 123

Sample Output:

Existing channel: 123
New channel: 456
New channel in db: 456 
channel in db: 123

This can happen if another process has already fetched the same client object and saved the object after your save operation.

In this case, the data in the second process still be the old one and overwrites your change when it saves.

please try to use celery here is Celery Documentation:- https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html

Back to Top