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?