Add SQL to every migration creating a field

27 views
Skip to first unread message

TheBeardedTemplar

unread,
Jun 8, 2016, 7:48:51 PM6/8/16
to Django users
Hey all,

I'll try to be as clear as I can with this problem - basically I am implementing soft-delete functionality in order to allow an 'undo' function that extends quite far into the past. My plan is to do it by creating a subclass of models.Model that looks like this:

class SoftDeleteModel(models.Model):
   
"""
    A subclass of the Django model object that is used to add safe-delete functionality.
    """

    deleted_on
= models.DateTimeField(blank=True, null=True, default=None, editable=False)


   
#Note that related_name '+' tells Django not to create a backwards relation
    deleted_by
= models.ForeignKey(UserModel, blank=True, null=True, on_delete=models.SET_NULL,
                                   editable
=False, related_name='+')

However I've run into an issue where many of my models have uniqueness constraints that I don't want to have violated by soft deleted objects. I'm using PostgreSQL and would like to do this using partial indexes so I can do something like this:

CREATE UNIQUE INDEX idx1 
  ON Post (name, obj_id, deleted_on) 
  WHERE deleted_on IS NULL;

So the unique constraint will only be violated if two objects have the same unique field and they haven't been deleted.

The problem is that I will likely have dozens or hundreds of SoftDeleteModel's in my database. I could manually modify each migration with a RunSQL statement but that would be time consuming. Is there a way that I could indicate that any SoftDeleteModel should create a migration that modifies each unique constraint into a partial unique constraint? Basically like an automatic custom migration?

Thanks
Reply all
Reply to author
Forward
0 new messages