Django - 从字段中删除唯一约束

时间:2017-09-01 09:52:52

标签: django postgresql

我有一个类似

的模型
class LoginAttempts(models.Model):
    user = models.OneToOneField(User, unique=False)
    counter = models.IntegerField(null=True)
    login_timestamp = models.DateTimeField(auto_now=True)

在db中创建的表就像

enter image description here

但是,如果我使用user_id = 362创建另一个条目,它将失败并显示IntegrityError: duplicate key value violates unique constraint。 Id已经是我的主键,我想让同一个用户拥有不同的计数器,而不是创建一个引用它们的新表,因为这是一个简单的表。

如何实现相同或最佳方式。我想将用户限制为指定数量的失败登录。

2 个答案:

答案 0 :(得分:2)

如果您想要一个允许用户使用多个LoginAttempt的关系,则不应使用OneToOneField。根据定义,这意味着每一方只有一个项目。相反,请使用ForeignKey

答案 1 :(得分:1)

OneToOneField的本质是它是一个具有唯一约束的ForeignKey

但是,如果您不想要单独的条目,请更新counterlogin_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'])
相关问题