How to avoid race condition with unique checks in Django

前端 未结 2 1986
予麋鹿
予麋鹿 2021-02-09 04:54

I have a simple model:

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


        
2条回答
  •  自闭症患者
    2021-02-09 05:42

    I agree with Tomasz Zielinski that common practice is to not worry about this. For most use cases it's just not worth the trouble.

    If it is important, the best way is probably with optimistic concurrency. In this case it might look like (untested):

    from django.forms.util import ErrorList
    
    def handle_form(request)
        form = InvitationRequestForm(request.POST)
        try:
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(...)  # redirect to success url
        except IntegrityError:
            form._errors['email'] = ErrorList()
            form._errors['email'].append('Error msg') 
    
        return render(...)  # re-render the form with errors
    

    SERIALIZABLE won't really help here. As the PostgreSQL documentation makes clear, you have to be prepared to handle serialization failures, which means that the code would look pretty much the same as above. (It would help, though, if you didn't have the unique constraint forcing the database to throw an exception.)

提交回复
热议问题