如何更新django中多个条目的唯一字段

时间:2017-05-19 18:55:52

标签: django django-models

我有一个类似的简单Django模型:

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')

请注意,other_test_field是唯一字段。现在我也存储了一些如下所示的数据:

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

我现在尝试做的就是切换这两个对象中的other_test_field字段,以便第一个对象具有" test2"第二个对象有" test1" for other_test_field。如何在保留唯一性的同时实现这一目标?最终,我试图批量更新数据,而不仅仅是交换两个字段。

由于唯一的约束违规,任何以串行方式更新数据的内容都会遇到IntegrityError,而且我不知道在添加它之前暂时删除此唯一约束的好方法。有什么建议吗?

0 个答案:

没有答案
相关问题