Django的 - 从场中删除唯一约束
问题描述:
我有一个像Django的 - 从场中删除唯一约束
class LoginAttempts(models.Model):
user = models.OneToOneField(User, unique=False)
counter = models.IntegerField(null=True)
login_timestamp = models.DateTimeField(auto_now=True)
表在数据库中创建一个模型就像是
但是如果我创建USER_ID = 362另一条目它以IntegrityError: duplicate key value violates unique constraint
失败。 Id已经是我的主键了,我想让同一个用户拥有不同的计数器,而不是创建一个引用它们的新表格,因为这是简单的表格。
如何实现相同或什么可能是最好的方法。我想限制用户指定的登录失败次数。
答
如果您想要一个允许用户使用多个LoginAttempt的关系,则不应使用OneToOneField
。根据定义,这意味着每边只有一个项目。相反,使用ForeignKey
。
答
OneToOneField
的本质是它是一个具有唯一约束的ForeignKey
。
但是,如果你不想单独的条目,然后更新counter
和login_timestamp
领域:
from django.utils import timezone
def update_attempts_for_user(user):
attempts, created = LoginAttempts.objects.get_or_create(user=user, defaults={'counter': 1, 'login_timestamp': timezone.now())
if not created:
attempts.counter += 1
attempts.login_timestamp = timezone.now()
attempts.save(update_fields=['counter', 'login_timestamp'])