简体   繁体   English

Django 条件唯一在一起

[英]Django conditional unique together

I have a model that looks like the following:我有一个如下所示的模型:

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)

Now, if I so a select where is_deleted=False , the combination of host_lib_song_id and owning_user should be unique.现在,如果我选择 where is_deleted=False ,那么host_lib_song_idowning_user的组合应该是唯一的。 How can I express this?我该如何表达?

Overriding validate_unique to check the uniqueness if is_deleted is False is more appropriate:如果is_deletedFalse则覆盖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)

You cannot express this through the Meta.unique_together constraint, but through django's model validation :你不能通过Meta.unique_together约束来表达这一点,而是通过django 的模型验证

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

You can use UniqueConstraint if you're using Django 2.2 +.如果您使用的是 Django 2.2 +,则可以使用UniqueConstraint You can see the full answer here .你可以在这里看到完整的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM