问题是这样的:
我有一个这样的模型:
class UserBook(models.Model):
user = models.ForeignKey(User)
book = models.ForeignKey(Book)
is_active = models.BooleanField(default=False)
class Meta:
unique_together = ("user", "book")
Run Code Online (Sandbox Code Playgroud)
显然,这个模型已经对现场用户和书籍有了独特的共同约束。数据库中可能会有一些这样的条目:
------------------------------
|user_id book_id is_active |
| 1 1 0 |
| 1 2 0 |
| 1 3 1 |
------------------------------
Run Code Online (Sandbox Code Playgroud)
我还要添加一个约束,即每个用户最多可以拥有一个is_active字段值为 1(True) 的条目。
目前我通过将模型更改为这样来解决这个问题:
class UserBook(models.Model):
user = models.ForeignKey(User)
book = models.ForeignKey(Book)
is_active = models.BooleanField(default=False)
key = models.charFeild(max_length=255, unique=True)
class Meta:
unique_together = ("user", "book")
def save(self, *args, **kwargs):
if self.is_active:
self.key = "%s_%s" …Run Code Online (Sandbox Code Playgroud)