简体   繁体   English

Django unique_together 不防止重复

[英]Django unique_together not preventing duplicates

I am clearly not understanding how to do this correctly, can someone set me straight.我显然不明白如何正确地做到这一点,有人可以让我直截了当。 Here is the model:这是模型:

class Team(models.Model):
   teamID=models.CharField(max_length=255) #this will be generated on the iPad
   name=models.CharField(max_length=255)
   slug=models.SlugField(max_length=50) 
   teamNumber=models.CharField(max_length=30)
   checkIn=models.DateTimeField(default=datetime.now())
   totalScore=models.IntegerField(max_length=6) 

   class Meta:
       unique_together = ("teamID", "name", "slug", "teamNumber", "totalScore")

If I submit twice in a row it saves all of it.如果我连续提交两次,它会保存所有内容。 Yikes!!!哎呀!!!

As aganders3 mentions the constraint is enforced at the database level;正如 aganders3 提到的,约束是在数据库级别强制执行的; I assume though that you are using a database like SQLite that doesn't support this kind of constraint.我假设您使用的是像 SQLite 这样不支持这种约束的数据库。

The reason that it all works as expected through the admin is that it is doing the uniqueness check itself (it doesn't rely strictly on the database to signal constraint violations).这一切都通过管理员按预期工作的原因是它本身正在执行唯一性检查(它不严格依赖于数据库来发出约束违规信号)。

You can switch to a database engine that supports this kind of uniqueness constraint (either MySQL or Postgres would work) or you could look at adding the check in using signals: http://djangosnippets.org/snippets/1628/您可以切换到支持这种唯一性约束的数据库引擎(MySQL 或 Postgres 都可以),或者您可以查看使用信号添加签入: http : //djangosnippets.org/snippets/1628/

Try the proper nested-tuple syntax ((foo,bar),) instead of just (foo, bar) ?尝试正确的嵌套元组语法((foo,bar),)而不是(foo, bar)

https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

Yes the paremeter unique_together receives as input a tuple of tuples, I have not tested tuples of more than two elements but it should work是的,参数 unique_together 接收一个元组元组作为输入,我没有测试超过两个元素的元组,但它应该可以工作

for your example:对于您的示例:

unique_together = (("teamID", "name"), ("slug", "teamNumber"))

or:要么:

unique_together = (("teamID", "name", "slug", "teamNumber", "totalScore"))

I found this approach helpful without adding any unnecessary fields我发现这种方法很有帮助,而无需添加任何不必要的字段

class Request(models.Model):
    user = models.ForeignKey(User, related_name='request_list', on_delete=models.CASCADE)
    requested_user = models.ForeignKey(User, on_delete=models.CASCADE)
    request_date = models.DateField(default=timezone.now())
    request_status = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        # Checking for duplicate requests
        try:
            request = Request.objects.get(user=self.user, requested_user=self.requested_user)
            raise ValidationError('Duplicate Value', code='invalid')
        except self.DoesNotExist:
            super().save(*args, **kwargs)

        # Checking for reversed duplicate requests
        try:
            request_new = Request.objects.get(requested_user=self.user, user=self.requested_user)
            raise ValidationError('Duplicate Value', code='invalid')
        except self.DoesNotExist:
            super().save(*args, **kwargs)

    def __str__(self):
        return self.user.username + '------>' + self.requested_user.username

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

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