无法从Django模型中的两个数据库中删除实例

时间:2015-04-09 15:37:22

标签: django django-models

当用户在管理员中删除模型时,我试图删除两个数据库中的模型实例。当他们创建一个新实例并保存它时,它会进入两个数据库。但是我无法从两个数据库中删除它,因为第一次调用delete会删除实例,因此第二次调用会抛出一个断言错误。有没有办法捕获实例并同时从两个数据库中删除它们?

class Change(models.Model):
    content = models.TextField()
    date = models.DateField(auto_now = True)

    def save(self):
        super(Change, self).save(using='default')
        super(Change, self).save(using='labs')

    def delete(self):
        #Here it is deleted from the default database.
        super(Change, self).delete(using='default')
        #This doesn't work because Ive deleted the instance. How do I get this to work as well?
        super(Change, self).delete(using='labs')

1 个答案:

答案 0 :(得分:0)

如果两个数据库都确定实例具有相同的pk值吗?如果是,则应在从第二个db中删除之前恢复实例的pk

def delete(self):
    pk = self.pk
    super(Change, self).delete(using='default')
    self.pk = pk
    super(Change, self).delete(using='labs')