开发者

Is there anything like unique_together(max_occurences=3)?

I have a model:

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

Now, I need something like unique_together(a,b, max_occurences=3) constraint to be added to the above model (so that there can be up to 3 values of c for each pair of (a,b), and开发者_运维问答 ideally those 3 values of c should be also unique for given (a,b)), but I don't know what to look for (and if something like this even exists in MySQL). Is there anything like that, or I have to do something like this:

 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')

-- and handle c1..c3 myself?


You should override the save() method for the model and check your constraint before each save and raise a ValueError if the constraint is violated.

 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜