I have these two models:
class Item(models.model):
space = models.OneToOneField(Space, null=False, on_delete=models.PROTECT)
class Space(models.Model):
...
An Item is linked to a single Space. A Space can only contain one Item.
I want to swap the Items:
item_1 = Item.objects.get(id=1)
item_2 = Item.objects.get(id=2)
space_1 = Item.objects.get(id=1)
space_2 = Item.objects.get(id=2)
assert(item_1.space == space_1) # True
assert(item_2.space == space_2) # True
# Switching spaces results in an IntegrityError (of course)
item_1.space = item_2.space
item_2.space = item_1.space
item_1.save() # IntegrityError
Item.objects.bulk_update([item_1, item_2], ['space']) # IntegrityError
I am now using a temporary Space that I create to swap the Items and that I delete afterwards. I was wondering if there's a more efficient way of swapping these Items' Spaces without running into an IntegrityError.