【问题标题】:Is there anything like unique_together(max_occurences=3)?有没有像 unique_together(max_occurences=3) 这样的东西?
【发布时间】:2011-03-10 05:43:44
【问题描述】:

我有一个模型:

 class MyModel(models.Model):
     a = models.IntegerField()
     b = models.IntegerField()
     c = models.IntegerField()

现在,我需要将 unique_together(a,b, max_occurences=3) 约束添加到上述模型中(这样每对 (a,b) 最多可以有 3 个 c 值,最好是这 3 个值c 对于给定的 (a,b) 也应该是唯一的,但我不知道要寻找什么(如果 MySQL 中甚至存在这样的东西)。有没有这样的事情,或者我必须做这样的事情:

 class MyModel(models.Model):
     a = models.IntegerField()
     b = models.IntegerField()

     c1 = models.IntegerField()
     c2 = models.IntegerField()
     c3 = models.IntegerField()

     class Meta:
         unique_together = ('a', 'b')

--自己处理c1..c3?

【问题讨论】:

  • 您应该考虑更好地对数据进行建模。

标签: sql mysql django django-orm


【解决方案1】:

您应该覆盖模型的 save() 方法,并在每次保存之前检查您的约束,如果违反了约束,则引发 ValueError。

 class MyModel(models.Model):
     a = models.IntegerField()
     b = models.IntegerField()
     c = models.IntegerField()

     def save(self):
         try:
             # Check values in model here
         except:
             raise ValueError("Cannot save more than 3 Cs with an A")
         super(MyModel, self).save(*args, **kwargs)

【讨论】:

  • 是的,但这很脆弱 - 黑客可能会开火,例如20 个同时请求并将他的统计数据提高到允许的水平以上。如果有的话,我更喜欢坚如磐石的数据库端解决方案。
  • 当时我唯一能想到的就是在数据库本身中完成一些事情。您应该关闭此问题并使用此模型的 SQL 版本在 PostgreSQL 或 MySQL 中打开一个新问题。不过,您必须单独维护它,而且它不是可移植的。无论如何,20 个同时请求不会允许用户超出 save() 方法。
猜你喜欢
  • 2013-07-30
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多