Wednesday, June 8, 2016

Add SQL to every migration creating a field

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/017bca80-5652-412a-bfba-a8bed7b0aa55%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment