UniqueConstraint messing with looped updates/creation

I have a UniqueConstraint checking three fields of a model (say, box).
I would like to quickly update few instances of box, or create new boxes under certain conditions.
I find that when I loop through the boxes in a queryset for this operation, the process fails sometimes with an error message that looks like this:

django.db.utils.IntegrityError: duplicate key value violates unique constraint "duplicate_boxes"
DETAIL:  Key (height, width, owner_id)=(8, 2, 888) already exists.

Strangely, this occurs when I am creating those boxes for the first time, in the loop … and sometimes the update process is truncated by this error resulting in mangled data.

Now, being sure that no box has a height below 10units

for height in range(10, 1):
    box = Box(
        owner=some_owner_instance,
        height=height,
        width=2,
    )
    box.save()

I get a unique constraint error for something like the above. Why? This thing is driving me crazy. There must be some trick or principle I need to learn here.

Sometimes, the few successful creations have height set to None when clearly, there should be a numeric value. Anytime I get the error, I am sure one of the new boxes will bear “None” but there are no duplicates for real. What is going on?

First, that for loop will execute 0 times. In that case, box is never being initialized or saved.

Please post the actual code that is running and generating the constraint error.

Oops …

correction.
for height in range(1, 10):

And you’re saying that if you run that loop in the Django shell it will generate the constraint error?

If so, please post the model here.

If not, please post the complete view in which this error occurs.

I eventually saw the cause of the issue. I was writing to a model from an external function while a view was attempting the same. Sorry for this. I thought it was an issue of concurrency in postgresql.