我的模型如下所示:
class LibraryEntry(models.Model):
host_lib_song_id = models.IntegerField()
song = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
album = models.CharField(max_length=200)
owning_user = models.ForeignKey(User)
is_deleted = models.BooleanField(default=False)
现在,如果我选择is_deleted=False
,那么host_lib_song_id
和owning_user
的组合应该是唯一的。我怎么能表达这个呢?
答案 0 :(得分:11)
如果is_deleted
为False
更合适,请覆盖validate_unique
以检查唯一性:
...
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)
答案 1 :(得分:4)
您不能通过Meta.unique_together
约束来表达这一点,而是通过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
答案 2 :(得分:1)
如果您使用的是Django 2.2及更高版本,则可以使用UniqueConstraint
。
您可以看到完整的答案here。