简体   繁体   中英

Django form integrityerror for concurrent operation on unique fields

I noticed a thing that I don't know if it is a real issue or I'm doing some wrong design.

I have a model:

class A(Model):
    name = CharField(unique=True, max_length=255)

and a modelform linked to A, this modelform has a clean_name() method, that checks if that field is unique in the db (ignore the fact that modelforms already do that by default, I'm specifying that for the example here).

In the view if I do

o = form.save(commit=False)
# xyz
o.save()

and in #xyz I have another client that inserts an A object with the same name field value, o.save() triggers an Integrityerror exception, correctly preventing the duplicate record to be inserted.

What I want to know is how to handle those cases, should I wrap that o.save() with a try/except block and then populate the error field on the form specifying to choose another name value?

This is somewhat a common case that should happen to everyone and that solution is horrible, so I think I'm doing something terribly wrong.

I suspect this might be the case:

Model forms provide uniqueness validation only when a flag is set in xx_clean() . If you override clean with your own (as you have), you need to call the superclass's clean() . See overwriting the clean method .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM