unique=True 给出已经存在!即使交换两个对象的值

unique=True gives already exist! Even if interchanging the values of two objects

为了按特定顺序显示对象(成员),我做了一个字段,order:

order = models.IntegerField(unique=True,null=True,blank=True)

这样我就可以 .order_by('order') 获得所需的订单。

在 Django Admin 中,table 只有两个对象 order 0,1。如果我想用 1,0 交换它,我会得到一个错误:

About us with this Order already exists

为了方便使用Django admin,有没有更好的方法来实现上面的?

您可以删除 unique=True 并添加自定义操作以重新排序对象。在这种形式下,Django admin 在单独的事务中应用每个对象,并导致此错误。您可以覆盖管理员 class 的更新功能,并在 this 等批量更新事务中进行所有更改。但我不推荐它。因为你以后可能会出错,想编辑其他字段而这一行出bug了。