django-safedelete
django-safedelete copied to clipboard
Support partial unique index
http://stackoverflow.com/questions/26410488/creating-partial-indexes-with-django-1-7
as described here, allow having a repeating unique index for a deleted and undeleted fields.
Do you have an exemple of what you would like to work? It seems to be something you would need to do on your models using safedelete, not on safedelete directly.
example implementation:
class SoftDeletableMixin:
def validate_unique(self, exclude=None):
if self.deleted:
return True
unique_checks, date_checks = self._get_unique_checks()
for model_class, unique_check in unique_checks:
lookup = dict(deleted=False)
lookup[field_name] = getattr(self, field_name)
for field_name in unique_check:
if self.objects.exclude(pk=self.pk)\
.filter(**lookup).exists():
raise ValidationError(
'Un-deleted order with same reference exists')
return True
This will work with django unique and Meta.unique_together constraints
What do you think? can I form a PR?
I'm still not sure what you really want to do. The issue with the unique check is that it would break in the database, not in django, because the object would be saved when a unique constraint is not correctly checked because the deleted objects are hidden from the queryset but still present in the DB.
We can support that with Postgres conditionally-unique-constraint and probably also for other DB(s).
The problem is that the alternative is lacking functionality.
For example: In a test, I want to clear state, delete a 'dirty' object and re-create it with the same unique ref (say using a data-provider for testing).
The result with the current implementation is that I will have to pass a new unique reference from the top of my head every time which introduces long lines of redundant code.
This is not something native supported by Django (as the RunSQL need show), so I don't think this is something we should implement in safedelete.
This is something you should implement on your own models. You can override _perform_unique_checks to meet your need.
Yes I am aware of the Django code structure, thank you. However I believe most users will not bother running custom SQL in their migrations, and having this out of the box could be nice.
Most users will not bother having special indexes. Safedelete only provide a mixin and does not have actual model (and thus no migration). If you want to have this out of the box, you should add this in Django first.
@BeOleg I had good experience with psqlextra's ConditionalUniqueIndex in such cases, you might want to look into https://django-postgres-extra.readthedocs.io/indexes/