user1410712
user1410712

Reputation: 185

Can't delete instance from two databases in Django model

I am trying to delete an instance of a model in two databases when a user deletes it in the admin. When they create a new instance and save it, it goes to both databases. But I can't get it to delete from both databases, since the first call to delete removes the instance, so the second throws an assertion error. Is there a way to catch the instance and delete them from both databases at the same time?

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

Upvotes: 0

Views: 74

Answers (1)

catavaran
catavaran

Reputation: 45575

Are you sure that the instance have the same pk value if the both databases? If yes then you should restore the pk of the instance before deletion from the second db:

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

Upvotes: 2

Related Questions