How to avoid race condition with unique checks in Django

前端 未结 1 1294
孤城傲影
孤城傲影 2021-02-09 05:08

I have a simple model:

class InvitationRequest(models.Model):
    email = models.EmailField(max_length=255, unique=True)
<         


        
1条回答
  •  长情又很酷
    2021-02-09 05:24

    The standard way is to NOT handle this, as:

    1. the probability of the failure in your case is close to 0;
    2. the severity of the failure is very low.

    If, for some reason, you have to be sure that the problem won't happen, you are on your own.

    I haven't analyzed the sequence of events in detail but I think that using the SERIALIZABLE isolation level won't really help, it will only cause IntegrityError (or DatabaseError) to be raised in a different place.

    Overriding Model._perform_unique_checks sounds to me like a bad idea, you better stay away from monkey patching if possible (and here it is possible).

    As for using the table lock to prevent unlikely errors... Well, I'm not a big fan so I cannot recommend that either.

    Here's a nice answer to a similar question: https://stackoverflow.com/a/3523439/176186 - I concur that catching IntegrityError and retrying is probably the easiest sane way to deal with the problem.

    EDIT: I found this: Symfony2 - how to recover from unique constraint error after form submission? and I agree with @pid's answer.

    0 讨论(0)
提交回复
热议问题