python - Django 条件唯一在一起

标签 python django model

我有一个如下所示的模型:

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)

现在,如果我选择 where is_deleted=Falsehost_lib_song_idowning_user 的组合应该是唯一的。我该如何表达呢?

最佳答案

覆盖 validate_unique如果 is_deletedFalse 则检查唯一性更合适:

...

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)

关于python - Django 条件唯一在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8245430/

相关文章:

python - 在 Django 中上传时调整两个图像的大小

python - Pandas .errors.EmptyDataError : No columns to parse from file

文件或无的 Python 上下文

python - ImportError : symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc. so.6 带链接时间引用

python - Django:在添加之前检查对象是否已经存在

ruby-on-rails - Rails Multi-Tenancy 应用程序的动态 ActiveRecord 模型标记

python - 如何刷新 IPython 中的打印语句

python - 将上下文从一个序列化程序传递到另一个序列化程序?

ruby-on-rails - 将缩略图链接到原始图像时未定义的方法 'to_model'

ruby-on-rails - 使用 RSpec 和 Rails 在模型中测试验证