Django conditional unique together
Overriding validate_unique
to check the uniqueness if is_deleted
is False
is more appropriate:
...
def validate_unique(self, exclude=None):
if not self.is_deleted and \
LibraryEntry.objects.exclude(pk=self.pk).filter(host_lib_song_id=self.host_lib_song_id, owning_user=self.owning_user).exists():
raise ValidationError('Some error message about uniqueness required')
super(LibraryEntry, self).validate_unique(exclude=exclude)
You cannot express this through the Meta.unique_together
constraint, but through django's model validation:
class LibraryEntry(models.Model):
def clean(self):
from django.core.exceptions import ValidationError
try:
# try to find a duplicate entry and exclude 'self'
duplicate = LibraryEntry.objects.exclude(pk=self.pk)\
.get(owning_user=self.owning_user,
host_lib_song_id=self.host_lib_song_id,
is_deleted=False)
raise ValidationError('Library Entry already exists!')
except: LibraryEntry.DoesNotExist:
# no duplicate found
pass