ORM model 'save' method and race condition / ACID Isolation


if we examine the following code:

class SomeModel(models.Model):
    def save(self, *args, **kwargs):

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        # Doing an ORM query on the model with *filter* on the model attributes & an associated model, 
        # and if exist - dont create a new instance, if not - create a new instance.

Now, it will work with the development server, but not with a production one like gunicorn or uvicorn, because the save method gurantee us atomicity, but not isolation, right?

for us to gurantee isolation, we should use ‘get_or_create’ on the view level?

I’m mistake somewhere?
Any comment will help, Thanks!

Actually, this isn’t necessarily true either. The development server can be subject to the same race conditions as your production server. (You generally don’t see them, because you don’t often run concurrent requests on it - but it can happen.)

Actually, I think you’re looking for update_or_create?

Regarding isolation though, you have the option to set the isolation level in your PostgreSQL database connections.

Also see Django DB Transactions

1 Like

It might be dependant on the situation, if some item exist we dont want to modify it ,iirc, so ‘get_or_create’ is more suitable.

need to take another look.


1 Like