How to update unique field for multiple records in django

I have a simple Django model like this:

class TestModel(models.Model):
    test_field = LowerCaseCharField(max_length=20, null=False,
                                verbose_name='Test Field')
    other_test_field = LowerCaseCharField(max_length=20, null=False, unique=True,
                                verbose_name='Other Test Field')

      

Note that other_test_field is a unique field. Now I also have some data that looks like this:

[
    {
        test_field: "object1",
        other_test_field: "test1"
    },
    {
        test_field: "object2",
        other_test_field: "test2"
    }
]

      

All I am trying to do is toggle the other_test_field fields in these two objects so that the first object has "test2" and the second object has "test1" for other_test_field. How do you do this while keeping it unique? I end up trying to update the data in bulk and not just replace two fields.

Anything that updates data in sequential order will get caught in an IntegrityError due to a unique constraint violation, and I don't know how I can remove the time constraint for that one operation before adding it back. Any suggestions?

+3


source to share





All Articles