Home > Enterprise >  How to handle network errors when saving to Django Models
How to handle network errors when saving to Django Models

Time:12-09

I have a Django .save() execution that loops at n times. My concern is how to guard against network errors during saving, as some entries could be saved while others won't and there could be no telling. What is the best way to make sure that the execution is completed?

Here's a sample of my code

# SAVE DEBIT ENTRIES
for i in range(len(debit_journals)):

    # UPDATE JOURNAL RECORD
    debit_journals[i].approval_no = journal_transaction_id
    debit_journals[i].approval_status = 'approved'
    debit_journals[i].save()

CodePudding user response:

Either use bulk_create / bulk_update to execute a single DB query, or use transaction.atomic as decorator for your function so that any error on save will rollback your database before your function was run.

CodePudding user response:

It depends of what you call a network error, if it's between the user and the django application or between the django application and the database. If it's only between the user and the app, note that if the request has been sent correctly even if the user lose the connection afterward the objects will be created. So a user might not have the request response, but objects will still be created.

If it's between the database and the django application some objects might still be created before the error.

Usually if you want a "All or Nothing" behaviour you should use manual transaction as described there: https://docs.djangoproject.com/en/4.1/topics/db/transactions/

Note that if the creation is really long you might hit the request timeout. If the creation takes more than a few seconds you should consider making it a background task. The request is only there to create the task.

See Python task queue alternatives and frameworks for 3rd party solutions.

  • Related