# How to exchange the key field in a transaction?

**URL:** <https://forum.djangoproject.com/t/how-to-exchange-the-key-field-in-a-transaction/15950>\
**Category:** Using the ORM\
**Created:** [September 13, 2022, 9:24am UTC](https://forum.djangoproject.com/t/how-to-exchange-the-key-field-in-a-transaction/15950 "2022-09-13T09:24:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![muiz](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/muiz/32/10065_2.png) [@muiz](https://forum.djangoproject.com/u/muiz)\
**Post date:** [September 13, 2022, 9:24am UTC](https://forum.djangoproject.com/t/how-to-exchange-the-key-field-in-a-transaction/15950/1 "2022-09-13T09:24:31Z")

</div>

class Test(models.Model):  
id = models.AutoField(primary\_key=True)  
name = models.TextField(null=False,blank=False, unique=True)  
class Meta:  
db\_table = ‘test’

Add two records to this table:  
r1 = Test()  
r1.name = ‘Tom’  
r1.save()

r2 = Test()  
r2.name = ‘Sam’  
r2. save()

Now I want to exchange the names in these two record in a transaction, how?

r1 = Test.objects.filter(id=1).first()  
r1.name = ‘Sam’

r2 = Test.objects.filter(id=2).first()  
r2.name = ‘Tom’

with transaction.atomic():  
Test.objects.bulk\_update([r1, r2], fields=[‘name’])

Previous code will raise an IntegrityError: ‘Sam’ is exists.  
How can I save these two record in a transaction?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [September 13, 2022, 10:55am UTC](https://forum.djangoproject.com/t/how-to-exchange-the-key-field-in-a-transaction/15950/2 "2022-09-13T10:55:04Z")

</div>

Use the old “three-step” exchange technique

- Change r1.name to some random unique value
- Change r2.name to the original r1.name value
- Change r1.name to the original r2.name value

It’s three db updates instead of two, but it does keep the constraints satisfied.

---

<div class="post-metadata">

**Author:** ![muiz](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/muiz/32/10065_2.png) [@muiz](https://forum.djangoproject.com/u/muiz)\
**Post date:** [September 14, 2022, 8:58am UTC](https://forum.djangoproject.com/t/how-to-exchange-the-key-field-in-a-transaction/15950/3 "2022-09-14T08:58:23Z")

</div>

Hi, KenWhitesell:  
Thank you for all your assistance. I use this method now.
